JavaScript - - By Roland Clemenceau

Localizing JavaScript Strings in a PHP MVC Framework

Today, I am going to show you how to efficiently localize your Javascript strings within your PHP Framework. You can download a working implementation of this tutorial here.

There are actually several methods to localize Javascript strings in a PHP environment. Technically speaking it is possible to duplicate your Javascript file, naming it after the target language, and loading the needed version each time the user selects a new language on site. But this surely represents a method that one could hardly call good practice, even though it would ‘work’.

The main disadvantage of using a method like this is that every time you will need to modify your JavaScript code then you will have to perform the modification for each language. This is only prone to error, if not bringing you extra unwanted work.

There is also the possibility to have your literal strings directly called by means of PHP variables embedded within your JavaScript code, but depending on your framework architecture, this is not always an option that’s available.

So I’m going to show you a method that will work for sure and which will be easy to maintain as well.

Remember, you can download a working example right here.

So let’s start…

In the example attached to this tutorial, I have set up a button that triggers a Javascript function called trigger_msg():

echo '<input type="button" value="'.$t_launch_message.'" class="trigger" onclick="return trigger_msg();" />';

The trigger_msg() function is found in /public/JS/main.js :

function trigger_msg(){
    return alert(translate(LOCALIZATION.here_is_how_it_works));
    }

– We call the translate() function found in /languages/translate.js and pass, as a parameter, the name of the element we need that’s contained in the array named LOCALIZATION.
– We’re using the syntax translate(name_of_language_array.name_of_element, extra_parameter1, extra_paramater2, etc…) thus using commas only to separate extra parameters.
– Parameters may of course be literals if surrounded by quotes

Before we take a deeper look at the translate() function, here’s what the LOCALIZATION array found in /languages/current_language/JS/current_language.js looks like:

var LOCALIZATION = {
    here_is_how_it_works :  'Voici comment cela fonctionne.\nAppuyez sur le bouton suivant afin de voir comment ça se passe avec des paramètres.',
    who_does_not_know_are_and_that_the_sky_is :  'Qui ne sait pas que %s x %s font %s,\net que le ciel est %s?',
    blue : 'bleu'
  };

Within our array element definitions you can see ‘%s’ is being used, that is the expression we use to hold our extra parameters. We will come to that a little later though.
Note that you may insert HTML style tags, eg. <b>, etc., within your array element definitions if you use a custom dialog box and it will work nicely.

Now time to concentrate on our translate() function:

(function () {
    
    if (!window.translate){
               
      window.translate = function(){
        var html = [ ]; 
        var arguments = arguments;
        var string = arguments[0];

        var objIndex = 0;
        var reg = /%s/;
        var parts = [ ];

        for ( var m = reg.exec(string); m; m = reg.exec(string) ) {  
          // m[0][0] gives undefined in IE
          parts.push(string.substr(0, m[0][0] === "%" ? m.index : m.index));
          parts.push("%s");
          string = string.substr( m.index+m[0].length );
        }
        parts.push(string);

        for (var i = 0; i &lt; parts.length; ++i){
            var part = parts[i];
            if (part &amp;&amp; part == "%s"){
              var object = arguments[++objIndex];
              if (object == undefined) {
                html.push("%s");
              }else{
                html.push(object);
              };
            }else{
              html.push(part);
            }            
        }

        return html.join('');
      }
    };
  })();

This function below constitutes the core of our JavaScript localization scheme.

Basically in the variable called string we store the arguments captured from the trigger_msg() function, parse them in our first for loop, filter them using a regular expression that’s held in the variable named reg, and push the resulting parts in an array called parts[]. Then we reassemble those parts into an array called html[] that our function returns.

The variable named reg holds a simple regular expression ‘/%s/’, the %s being the syntax we have chosen to use to define our parameters as discussed above.

The trigger_msg_with_params() function in /public/JS/main.js shows just how to use parameters when localizing your strings. Indeed, there are times in a system when a literal string that needs to be translated may contain values which will depend on user input, and this function comes in handy by allowing to not having to re-use our code so much:

function trigger_msg_with_params(){
    var param1 = 5382;
    var param2 = 9408;
    var param3 = param1 * param2;
    var param4 = translate(LOCALIZATION.blue);
    
    return alert(translate(LOCALIZATION.who_does_not_know_are_and_that_the_sky_is, param1, param2, param3, param4));
    }

You can see each defined parameter, eg. var param1, could well have been a parameter passed to the function call too. Defined parameters can also be actual calls to the translate() function. All of which, again, turns out to be very helpful.

That’s all there is to it. This system represents an efficient and reliable way to translate your JavaScript strings across your PHP Framework and allows for a great deal of suppleness.

You are more than welcome to leave your comments or questions. Stay tuned for more tutorials.