The easiest way to localize SPA application using polyglot.js

For a long time ago when I was a teenager with long black hair excited with new Flash page, there wasn’t such thing like web page localization with JavaScript. Indeed, there weren’t any JavaScript-intensive pages to localize.

But at the age where JavaScript got triumph and each kid makes their own framework you can be encountered with such question.

Firstly, your should google and find library to localize your application. I found polyglot.js but your can find something similar.

Then create your_locale.json file in js/locale directory (or something elswhere)


"sign_in": "Sign in"

Next include the code below somewhere you want

  //Obtain locale from somewhere (cookie, localstorage, url ...)
  var locale = getLocale();
  // Gets the language file.
  $.getJSON('js/locales/' + locale + '.json', function(data) {
    // Instantiates polyglot with phrases.
    window.polyglot = new Polyglot({phrases: data});

That’s great but we have to use it in our favourite template engine preferably with handlebar moustache logo:

      return polyglot.t(str);

Now we can use it in our templates files like this

  <a href="/sign_in" class="sign-in">{{t 'sign_in'}}</a>

That’s it!

Related Posts

Golang and OpenAPI(Swagger). How to create documentation for your REST API services

Game of Code Review. How code review can improve the health of your team

Active Admin custom JavaScript for diverse pages

Simple hack to add per page JS to active admin

Presenters in javascript

An article describing using presenters in your javascript code

Deploying rails apps, part 3. Configuring capistrano, nginx with puma

The third article of deployment series. Configuring capistrano, nginx with puma

Deploying rails apps, part 2. Setting up the necessary software

The second article of deployment series. Setting up the necessary software.

Deploying rails apps, part 1. Bootstrap the server

The first article of deployment series. Bootstrap the server.