Last Updated: February 20, 2018
·
7.017K
· alexandrosd

Internationalized JavaScript files in CodeIgniter

There are many reasons for which strings inside JavaScript files need to be in user's language.

CodeIgniter has its own i18n library, however it can be used only in PHP. The solution to internationalized JavaScript files is a file parser.

Just create a new controller (under /application/controllers) named whatever you wish (i.e. JSLoader):

class JSLoader extends CI_Controller {
function __construct() {
    parent::__construct();
    $this->load->helper('file');
}
public function file($file = null){
    if (!$file) {
        header('HTTP/1.1 404 Not Found');
        return;
    }
    $contents = read_file('./javascripts/' . $file);
    if (!$contents) {
        header('HTTP/1.1 404 Not Found');
        return;
    }
    $contents = $this->parse_variables($contents);
    echo $contents;
}

private function parse_variables($text) {
    preg_match_all("/\[@{0,1}[a-zA-Z0-9_]+[\s]*[a-zA-Z0-9_]*\]/",$text, $matches, PREG_PATTERN_ORDER);
    foreach ($matches[0] as $match) {
        $varname = str_replace('[', '', $match);
        $varname = str_replace(']', '', $varname);

        $lang_value = lang($varname); // get value from lang file

        $value = ($lang_value ? $lang_value : $varname);

        if ($value) {
            $text = str_replace($match, $value, $text);
        }
    }
    return $text;
}   
  }

The above code will search your JavaScript files for strings encapsulated in braces ([ ... ], i.e. [VAR1], [VAR2]). These variables, along with the braces, will be replace with the value provided in the active language file.

// This will display an alert window,  
// having as text the value of
// $lang['HELLO_MESSAGE'] variable
// in your CodeIgniter language file.
function someJavascriptMethod() {
   alert('[HELLO_MESSAGE]'); 
}

You may then load JavaScript files in your html views by making references to your new controller:

<script type="text/javascript" src="<?php echo site_url('jsloader/my_javascript_file.js" />

3 Responses
Add your response

That's a pretty cool idea!

But instead of just echoing the output, you should rather use:

$this->output
            ->set_content_type('text/javascript')
            ->set_output($contents);

Also there's an error in the last of your snippets. It need to be:

<script type="text/javascript" src="<?php echo site_url('jsloader/my_javascript_file.js');?>" />

And maybe someone will this thing for the routes.php, too:

$route['jsloader/(:any)']           = "jsloader/file/$1";
over 1 year ago ·

I also change the loop in the parse_variables for this other (sorry, I don´t find how "shortcode" the code):

foreach ($matches[0] as $match) {
$varname = strreplace('[', '', $match);
$varname = str
replace(']', '', $varname);
$langvalue = lang($varname); // get value from lang file
if ($lang
value)
$text = strreplace($match, $langvalue, $text);
}

A reason for this change is that if someone is using a javascripty array and make something like: myarray[0], or inside a loop like myarray[index], the original code would change [0] for 0 and [x] for x, and the result would be myarray0 and myarrayx and it throw an error.

Thanks for this solution.

over 1 year ago ·

Instead of using i18n library, it is better to use CodeIgniter's language library. The process is really easy. You have to enable hooks and use language loader and switcher classes. For URL, you can use autoload helper. Source: https://www.cloudways.com/blog/multi-language-codeigniter/

over 1 year ago ·