In many systems I have noticed that there are global variables in JS that are
placed in the head with the translations. There is a technique to work with
thereby?
Make it clear: This is not a tutorial. You must know by now framework, and I’ll just exemplify the passage of a variable from $_SESSION
to the JavaScript
using the native tools of Codeigniter. I didn’t care much for safety either, but I don’t think there’s any gross flaw in that code.
The goal is for you to understand how to assign session data PHP
to a variable JavaScript
, which, if I understand correctly, answers your question. That is, we will manipulate the value of the variable JavaScript
as amended in PHP
.
So use Sessions, Hooks and helpers. The hook will set the default session value for the variable. O helper will recover this value to the Javascript and print in the document HTML
.
- Enable use of session library:
I like autoload: get into application/config/autoload.php
and insert Session in the array correspondent: $autoload['libraries'] = array('session')
.
- Defining available languages:
These data can, logically, be loaded from your database. In the example I will define the array $config['langs']
to serve as a reference. Enter application/config/config.php
and insert this: $config['langs'] = ['pt-br','en','es'];
.
Thus, these are the only hypotheses available for the method set_lang_var()
that defines the language.
- Enable and create a hook:
Enable the use of Hooks defining $config['enable_hooks'] = TRUE;
in the archive application/config/config.php
;
Within application/config/hooks.php
insert the following:
$hook['post_controller_constructor'][] = array(
'function' => 'set_lang',
'filename' => 'set_lang.php',
'filepath' => 'hooks'
);
Now create the hook application/hooks/set_lang.php
and insert the following:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
function set_lang() {
$ci = & get_instance();
//$ci->session->unset_userdata('lang');
if(NULL == $ci->session->userdata('lang')){
//Se nao houver idioma na session, define o idioma padrao
$userdata = ['lang'=>'pt-br'];
$ci->session->set_userdata($userdata);
}
//Caso contrario, o metodo teste/set_lang_var() pode ser usado para mudar o idioma
}
From this point on PHP
already know which is the default language. Now it will be necessary to make the system pass the data of $_SESSION
of PHP
for a variable JavaScript
readable.
- Enabling and creating a helper:
To use the helpers you must carry them. I like to use autoload: inside application/config/autoload.php
add the helper string at the array appropriate: $autoload['helper'] = array('string')
;
It is good practice not to change the original scripts of framework, then stretching the helper to be able to work without fear: create the file application/helpers/MY_string_helper.php
and insert the following:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
if (!function_exists('string_lang')) {
function string_lang(){
$ci = & get_instance();
echo '<script type="text/javascript">';
echo "var lang='".$ci->session->lang."'";
echo "</script>\n";
}
}
- Controller, methods and view:
The controller application/controllers/Teste.php
has two very simple methods:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Teste extends CI_Controller {
function get_lang_var(){
$data['title'] = 'get_lang_var()';
$this->template_action = strtolower(__CLASS__."/".__FUNCTION__);
$this->load->view($this->template_action, $data);
}
function set_lang_var(){
$lang = $this->uri->segment(3, 0);
$userdata = ['lang'=>$lang];
if(in_array($lang, $this->config->item('langs'))){
$this->session->set_userdata($userdata);
redirect('teste/get_lang_var');
}
else{
redirect('teste/set_lang_var/pt-br');
}
}
}
To view application/views/teste/get_lang_var.php
is also quite simple:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<?= doctype('html5'); ?>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title><?= $title ?></title>
<base href="<?= config_item('base_url') ?>">
<?=string_lang()?>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<style>body{padding-top: 20px;}</style>
</head>
<body>
<div class="container">
<p>Mude o idioma: <?=$_SESSION['lang']?></p>
<?=anchor('teste/set_lang_var/pt-br', 'pt-br')?>
<?=anchor('teste/set_lang_var/en', 'en')?>
<?=anchor('teste/set_lang_var/es', 'es')?>
</div>
</body>
</html>
Watching the browser console (or the page’s source code) will be possible to realize that the variable <script type="text/javascript">var lang='pt-br'</script>
changes value whenever you choose a new language.
That’s it. Study this code and you’ll get a sense of how to do it in other ways, or apply the concept to the libraries you’re using.