A Step-by-Step Guide to JavaScript Localization

Today it's time to talk about front-end. We will discuss how to localize JavaScript applications using jQuery.I18n by Wikimedia, Polyglot by Airbnb and Globalize by jQuery team.

Internationalization (dubbed as I18n) and localization (dubbed as L10n) are very important (though often hard) steps for any application that is going to be used worldwide. In one of the previous articles we’ve seen how to implement I18n at the back-end powered by Ruby on Rails, but today it’s time to talk about front-end. In this article we will discuss how JavaScript Localization for applications works using the following solutions:

  • jQuery.I18n by Wikimedia
  • Polyglot by Airbnb
  • Globalize by jQuery team

All of these solutions are quite different and have their own specifics so we’ll see them all in action.

The source code is available at GitHub.

Preparations for JavaScript Localization

Before proceeding to the main part let’s quickly prepare a basic structure for our simple JavaScript Localization demo project. Create a separate folder with the index.html file inside. We’ll make copies of this file to test various solutions. Then create a nested folder called common and inside place the jquery.js file that can be downloaded from the jquery.com website. You may pick either version of jQuery (1, 2 or 3) depending on what browsers you wish to support – it does not really matter for this demo.

Now populate index.html with some markup:

index.html

This is enough for us to get started!

jQuery.I18n

Let’s start with a jQuery-based internationalization library developed and maintained by Wikimedia. Wikimedia is a global movement which takes care of such well-known projects as Wikipedia, Wikinews, Wikibooks and others. jQuery.I18n, in turn, uses a JSON-based localization file format and supports gender, grammar forms, dynamic change of language, fallback chains and more.

Translations for jQuery.I18n can be separated in multiple files (en.json, de.json etc) or stored all together in one file. Here is an example of en.json:

So, as you can see, these files support metadata where you specify authors, date of the latest update, locale and other information. Next you provide the actual translations in a key-value format. It is best practice to prefix keys with the app’s name to make it unique, but that’s not mandatory.

For smaller apps you may provide all translations in a single file. In this case language’s name is specified as a parent key:

What’s more, you can even provide path to the translations file:

Now, of course, you are wondering how to load these translations into your app. There are a couple of ways and the first is probably the easiest one. Instead of creating a separate JSON file you can place all translations directly into the script by passing them to the load function:

I can’t say that this is a recommended practice but for really small projects it is fine.

Another solution is to load messages from an external URL

When using this approach the load will return, so you can place further actions inside the done function:

You can set the locale upon library’s initialization using either locale option

or by providing it inside the lang attribute for the html tag:

Of course, locale can be switched later by redefining the locale option:

To translate a message you would provide a key to the $.i18n function

or just employ a data- attribute (no additional JavaScript is needed). The initial content is a fallback text to display in case something goes wrong and the translation cannot be found:

  • Fallback text

 

Note that messages support interpolation by taking parameters. These are written as $1, $2 etc:

Plurals and genders are handled with the following syntax:

In Practice

To start off, copy our base index.html file as the jquery_i18n.html. Create a new jquery_i18n directory and place the main-jquery_i18n.js file inside. Next clone jQuery.I18n somewhere on your PC along with sub-modules:

We will require all files from the src directory (without the languages folder) and also CLDRPluralRuleParser.js from thelibs\CLDRPluralRuleParser\src. Copy all of these into the jquery_i18n folder and then include them in the proper order:

jquery_i18n.html

Let’s also provide the initial locale via the lang attribute:

jquery_i18n.html

Lastly, add links to switch the language and a couple of empty tags that are going to host our translated content. I’ll work with English and Russian but of course you may choose any other languages – it does not really matter, but for real-world apps make sure your texts are properly translated, preferably by a human.

jquery_i18n.html

 

 

Now proceed to the script. We’ll need to load translations as soon as the document is ready. For simplicity let’s store all our messages in the script:

main-jquery_i18n.js

Note the welcome key – the same name is used in the data-i18n attribute for the h1 tag. This way a proper translation will be used automatically – all we have to do is run this process by calling the i18n() function. I’ll extract it inside theupdate_texts:

main-jquery_i18n.js

Now let’s take care of language switching. This is simple – just listen to the click event, extract value of the data-localeattribute and then set locale accordingly:

main-jquery_i18n.js

Lastly, we are going to add a translation for the #messages section. This is going a be a bit more complex:

main-jquery_i18n.js

Here pluralization and gender info are used at the same time. For Russian language I had to add more options because pluralization rules are more complex. In order for this to work tweak the update_texts() function:

main-jquery_i18n.js

Now open the page and try to switch between languages – everything should be working just great!

Polyglot.js

Polyglot.js is a small solution created by Airbnb (an engineering company) that works in browser and in Common.js environments. It supports interpolation and pluralization while having zero dependencies. Grab production version here.

To start working with Polyglot, instantiate it:

It’s a class-based, therefore you may work with a different sets of locales at the same time.

Next provide a list of phrases:

As a common pattern, documentation suggests to prepare a hash of phrases on the back-end and then output them in thescript tag. Note that Polyglot won’t do translation – it’s your job to give proper phrases based on users’ locale.

Phrases can be replaced or removed completely (for example, to free up memory) by using replace or clear methodsrespectively.

Note that nesting is supported as well:

If you’ve come from the Rails world, interpolation should look familiar to you:

To perform the actual translation, utilize the t method:

If your key is nested, then use dot . as a delimiter:

Note that language’s name is not provided anywhere – currently it is used only when working with pluralization. To set it, employ the locale function

or set it upon instantiating a new object by passing a locale option.

Messages with pluralization should be delimited with four pipes (||||):

The correct message will be picked based on the smart_count parameter.

In Practice

Now let’s quickly see this solution in action. Copy index.html file and name it polyglot.html. Then create a polyglot folder and place the production version of the script inside. Also create the main-polyglot.js file there and hook everything up:

polyglot.html

For this demo we will utilize Underscore.js’ template engine that will be used to render content (though you may stick withHandlebars or some other solution). If you haven’t worked with such templates before, the idea is pretty simple: you have a markup with some parameters. This template is then being “compiled” (meaning that the parameters receive their values) and rendered on the page like any other HTML.

Place the production version of Underscore into the common folder and require it:

polyglot.html

I am going to place our template directly onto the page, at the very bottom. Note that it has to be wrapped with a script tag with a special type (to prevent browsers from trying to process it as a JavaScript code):

polyglot.html

Now inside the script let’s wait until the document is ready and then instantiate the Polyglot class while providing two messages:

main-polyglot.js

Here we utilized interpolation and pluralization (note the parameter’s name smart_count – when using another name the pluralization seems to stop working). Now let’s grab the template

and then provide values to the parameters inside it

Here is the resulting code:

main-polyglot.js

Load the HTML document and test it out!

Globalize

Globalize is a pretty big library for internationalization developed by the members of jQuery core team. It works in browser (supporting all modern browsers and IE starting from version 9) and with Node.js, providing many useful features including number, date and time parsing, pluralization, interpolation, unit support and much more. It uses Unicode CLDR that provides key building blocks for software to support the world’s languages, with the largest and most extensive standard repository of locale data available. What’s more, Globalize is modular and does not contain any I18n data – you are free to load it yourself.

There are three main API functions:

  • Globalize.load() that loads CLDR locale data in JSON format (such as date and time formats, names of the month etc)
  • Globalize.locale() – getter and setter for the locale
  • [new] Globalize – instantiates a new Globalize object

Also there are variety of different functions for each module that you can find here.

In Practice

Let’s see Globalize in action right away. Copy index.html and name it globalize.html. Also create the globalize folder with theglobalize-main.js file inside. As long as Globalize is modular, dependencies has to be loaded in the proper order (there is even an online tool available helping you to find out which dependencies are needed).

Therefore, you’ll need to download the latest version of Globalize as well as CLDR. Here is the list of Globalize’s files to grab (place them inside the globalize folder of your project):

  • dist/globalize.js
  • dist/globalize/date.js
  • dist/globalize/number.js
  • dist/globalize/currency.js
  • dist/globalize/message.js
  • dist/globalize/plural.js

Unfortunately, that’s not all. Here are the required CLDR files that has to be placed inside cldr folder (create it now):

  • dist/cldr.js
  • dist/cldr/event.js
  • dist/cldr/supplemental.js

Phew. The last part is providing some common locale data for CLDR – download it here and place under the cldr/cldr_data.jsname. Finally, hook all those files in the proper order:

globalize.html

Also add a couple of placeholders for our content:

globalize.html

 

 

Now let’s load a welcome message:

globalize-main.js

Here we are using the message-formatter module. Next instantiate the Globalize class

and populate the #welcome section:

Note that messageFormatter returns a function that we then call and pass the object containing a name. This can be re-written as

Actually, message’s parameters do not need to be named – you may say 0, 1, 2 etc instead:

In this case pass an array to the formatter:

Next provide another message containing the today’s day and total earnings:

In this example we’ll use date and currency formatters:

When formatting the currency, we pass USD as the second argument. This argument is used to display a proper symbol when rendering the result. The symbol itself was defined inside the clrd_data.js file:

medium is the name of the datetime format – it was also defined inside the clrd_data.js file as

Here 1 is the date and 0 is time. Date and time, in turn, are formatted using the following masks:

Now that everything is ready you can observe the result!

PhraseApp Saves the Day Once Again

Managing translations for multiple languages can be tedious indeed. With PhraseApp, however, the whole process becomes much simpler.

Grab your free trial if you have not signed up already and create a new project. PhraseApp supports a great range of various formats from simple to nested JSON (and specific formats for AngularJS or React). Next just add as many locales as you need and upload existing JSON files with translations if you have any.

Having done that you will be able to quickly understand which translations are missing, manage your keys and messages as well as download updated translations with one click. What’s even cooler, you can easily request support from professional translators (which is probably better as localization is not only about translation). Therefore, I really encourage you to give PhraseApp a try!

Conclusion

So in this article about JavaScript Localization we’ve taken a look at various solutions helping you to localize your app: jQuery.I18n, Globalize and Polyglot. Polyglot appeared to be the smallest and simplest library, whereas Globalize and jQuery.I18n are quite big and complex – it’s up to you which one pick!

Hopefully, you found this article useful and interesting. Thanks for staying with me and happy coding!


Also published on Medium.

Comments