Sunday, April 10, 2016

Internationalization Using jquery.i18n.properties.js

Internationalization refers to automatically showing localized text in application pages for users visiting the site from different regions in the world or localizing the site content based on the language preference chosen by the user.

Getting jquery.i18n.properties.js

First of all we need to download the plugin.

A minified version of the same is available at http://code.google.com/p/jquery-i18n-properties/downloads/list
Steps For Internationalization

The first step as with all JavaScript libraries is to include the JavaScript into HTML. Jquery.i18n.properties.js is a jQuery plugin; hence we need to include jQuery also into HTML before jquery.i18n.properties.js like shown below:
<HEAD>
        <script type="text/javascript" src="js/jquery-1.10.2.js"></script>
        <script type="text/javascript" src="js/jquery.i18n.properties.js"></script>
</HEAD>
The sample HTML is given below:
<BODY>
        <h2>Internationalization using jQuery.i18n.properties</h2>
        <div id="langBox">
            Language:
            <select id="lang">
                <option value="en" selected>en</option>
                <option value="tr">tr</option>
                <option value="fr">fr</option>
            </select>
        </div>
        <div id="lWelcome">Welcome to My Site!</div><br>
        <div id="lSelLang">Your Selected Language is: en </div>
</BODY>
The jquery.i18n.properties.js plugin consumes .properties files for doing text translations. The sample of properties file is mentioned below:

Messages_fr.properties
lWelcome = Bienvenue sur le site de démonstration !
lSelLang = Votre langue sélectionnée est : {0}
Messages.properties
lWelcome = Welcome to my Site!
lSelLang = Your Selected Language is: {0}
Messages_tr.properties
lWelcome = Benim Sitemize Hoşgeldiniz !
lSelLang = Sizin Seçili Dil geçerli: {0}

Loading localized strings from .properties

The below code sample is used to load the resource bundle properties file using jquery.i18n.properties.js
$(function() {  
  $.i18n.properties({ 
    name: 'Messages', 
    path: 'bundle/', 
    mode: 'both', 
    language: lang, 
    callback: function() { 
      $("#lWelcome").text($.i18n.prop('lWelcome')); 
      $("#lSelLang").text($.i18n.prop('lSelLang', lang)); 
    }
  });
});

Advantages of jquery.i18n.properties.js


  • The main advantage of this plugin is that it uses .properties files for internationalization. This is helpful as same properties files could be shared with other parts of the program.
  • The support of parameterization of strings is also beneficial as this enables one to have complex multilingual strings.
  • Has option to use map as well as JavaScript variables/functions for retrieving translated strings.
  • The plugin is very lightweight and can be easily used with any HTML as it is jQuery based.