Over a million developers have joined DZone.

What Every Developer Should Know About JQuery I18n

An excellent JavaScript internationalization solution is called jQuery.i18n. Learn all you need to know to translate your jQuery application.

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

An important consideration when designing a website is internationalization. Each region and country around the world has different expectations when it comes to how text, messages, numbers, and dates should appear. Each user of a particular application expects that all text and messages are displayed in a familiar format. JavaScript has an excellent internationalization solution called jQuery.i18n. jQuery i18n is used for localization of MediaWiki and many other international websites.

Features of JQuery I18n

  • Keeps code separate from i18n content. This feature keeps the code modular and allows developers to load the i18n functionalities they need.
  • Uses the JSON format.
  • It allows a change in a language without refreshing the web page.
  • Handles the plural form without using additional messages. Rule handling is done using the Unicode Consortium’s Common Locale Data Repository (CLDR).
  • Corrects sentences according to gender by passing the gender value.
  • Supports grammar forms.

JQuery I18n Directory

The conventional way of formatting your directory with jQuery i18n is to have an i18n folder with the JSON file for each language code stored in this directory. An example directory is displayed in Figure 1.

file-system-2

Figure 1. Directory with JSON files for each language code.

JQuery I18n Message File Format

jQuery i18n uses JSON files, which allow the user to store information in a lightweight format for data exchange. JSON files are advantageous because:

  1. They allow an easy way for translators to access text to be translated. This is very useful if the JSON files need to be sent out for translation services.
  2. They prevent direct access to the database.

The JSON file is comprised of a series of name-value pairs or an ordered list of values. In a JSON file for internationalization, the messagekey-message pairs contain the names and values for all language pairs. Every key is in lowercase letters with “-“ separating the words, and is associated with a value in the chosen language. The JSON file can include @metadata, which stores non-message information about the file, such as copyright and author information. A separate JSON file is often created for each language type; however, all of the translations can also be put into a single file. The advantage of separate JSON files is that the files are less complex. However, a single JSON file helps to ensure that the fields are not duplicated while embedding multilingual data. An example JSON file with a single language and @metadata is provided below:

An example JSON file with multiple languages and @metadata is provided below:

{
"@metadata": { 
"author": "Colleen", 
"description": "An example JSON file",
"last-updated": "2016-09-21",
"message-documentation": "qqq"
},
"greeting": "Hello",
"bye": "Goodbye"
}



An example JSON file with multiple languages and @metadata is provided below:

{ 
"@metadata": {
"author": "Fred",
"description": "An example JSON file",
"last-updated": "2016-09-21",
"message-documentation": "qqq",
"arrayGroups": {
"label": {
"en": "label_en",
"fr": "label_fr"
}
}
},
"en": {
"greeting": “Hello”,
"bye": "Goodbye"
}
"fr": {
"greeting": “Bonjour”,
"bye": "Au revoir"
} 
 } 

Usage

Some of the ways that jquery.i18n can be used are shown in the table below.

Usage Area Description
Switching locale The locale for the web page can be obtained using the locale option:

$.i18n( {

   locale: ‘fr’ // Locale is French

} );

To switch to another locale after plugin is initialized: 
$.i18n ().locale = ‘ml’;

Message Loading Messages can be loaded for a specific locale or more than one locale.

$.i18n().load( {

} );

Data API Localized messages can be displayed without JavaScript.

<li data-i18n=”message-key”></li>.

Message Format – Placeholders These parameters are represented by the $1, $2, $3 in the messages, syntax {{PLURAL:$1|pluralform1|pluralform2|…}} and are replaced by run-time.
Message Format – Plurals In English, there are only two plural forms, but in many other languages, there are more than two plural forms.
Message Format – Gender {{GENDER…}} syntax

With the gender of placeholders, the syntax changes dynamically.

Translation

There are several ways to translate a jquery.i18n application:

  1. Editing the JSON files. This is suitable for small applications with a limited number of languages.
  2. Have a translation interface with the application. This option works for proprietary or private applications with many translators.

JQuery.I18n.Properties

jQuery.i18n.properties is a jQuery plugin for internationalization. Similar to Java, jquery i18n uses resource bundles (‘.properties’ files). Resource bundles are used to store locale-specific information such as text messages. They allow an easy way of accessing locale-specific information and adding locales easily by adding additional resource bundles. The ‘.properties’ files contain locale-specific key-value pairs and interprets these files based upon language and country codes.

Using Jquery.I18n.Properties

The jquery.i18n.properties.js plugin can be downloaded from https://github.com/jquery-i18n-properties/jquery-i18n-properties. The plug-in should be included in the <head> section of your HTML page. The version of jquery that you use should be specified in the source file as follows.


<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>

Features Of JQuery.I18n.Properties

  • Works like Java i18n. Uses resource bundles (‘.properties’ files) for translations. Uses ISO-639 for language codes and ISO-3166 for country codes.
  • If no language is specified, uses the default browser language. The default language in the resource bundles is always used first. The user-specified language will be loaded next.
  • The resource bundle strings allow placeholder substitution, and there is support for namespaces in the keys.

Language Control

To make your code more efficient with less 404 errors, a languages.json file should be used. A languages.json file defines the languages and the properties files that can be used. The languages.json should be placed into the same directory as the language properties files. An example of a languages.json file is as follows:



{    
  "languages": [
    "en_GB",
    "es_ES",
    "pt_BR",
    "sv_SE"    
  ] 
{




Example Using JQuery.I18n.Properties

To create an HTML page using jquery.i18n.properties.js, the first step is to create a directory with the desired folders for the JavaScript files and the properties files. For this example, we will use the directory in Figure 2.

file-system-1

Figure 2. Directory using properties files.

Next, the HTML code will be created. The HTML contains a dropdown that allows the user to select a language. The messages below the dropdown are localized based upon the language chosen.


<HTML>   

<HEAD>        
  <script src="js/jquery-3.1.0.js" ></script>
  <script type="text/JavaScript" src="js/jquery.i18n.properties.js"></script> 
 </HEAD>   
  <BODY>        
    <h2>Internationalization Example Using jQuery.i18n.properties</h2>
    <div id="langBox">
      Language:            
      <select id="lang">                
        <option value="en" selected>English</option>                
        <option value="tr">Turkish</option>                
        <option value="fr">French</option>            
      </select>        
    </div><br>        
    <div id="lWelcome">Thank you for reading this example</div><br>        
    <div id="lSelLang">Your Selected Language is: en </div>   
</BODY>   

</HTML>

Define .Properties Files

The jquery.i18n.properties.js plugin uses .properties files for the translate text. There are three properties files used in this example: (1) Messages.properties, (2) Messages_fr.properties, and (3) Messages_tr.properties. The text in each properties files is shown below:


Messages.properties 
lWelcome = Thank you for reading this example
lSelLang = Your Selected Language is: {0}     


Messages_fr.properties 
lWelcome = Merci d'avoir lu cet exemple 
lSelLang = Votre langue sélectionnée est : {0}     


Messages_tr.properties 
lWelcome = Bu örnek okumak için teşekkür ederiz 
lSelLang = Sizin Seçili Dil geçerli: {0}

Loading Localized Strings From .Properties

To load the messages from the properties files, save the jquery.i18n.properties.js file in the js folder. The jquery.i18n.properties.js code below is a simple example of how the properties files are loaded.

Options

Option Description Notes
name File name or portion of the file name that represent a resource bundle. Optional String or String[]
language The ISO-639 Language code (‘en’, ‘fr’) and, optionally, ISO-3166 country code (‘en_US’, ‘pt_BR’). If not specified, the default language reported by the browser will be used. Optional String
path Path to directory that contains ‘.properties‘ files to load. Optional String
mode Option to have resource bundle keys available as JavaScript vars/functions OR as a map. Optional String
cache Bundles are cached by the browser or forcibly reloaded. The default is to forcibly re-load. Optional boolean
encoding Type of encoding for bundles. Property file resource bundles are specified in ISO-8859-1 format. Defaults to UTF-8 format. Optional String
callback Callback function is called when script execution is completed. Optional function()

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:
jquery ,web dev

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}