How to make i18n with Handlebars.js (mustache templates)?

mdcarter picture mdcarter · Oct 13, 2011 · Viewed 32.7k times · Source

I'm currently using Handlebars.js (associated with Backbone and jQuery) to make a web app almost totally client side rendered, and I'm having issues with the internationalisation of this app.

How can I make this work?

Are there any plugins?

Answer

poweratom picture poweratom · Jan 10, 2012

I know this has been answered, but I'd like to share my simple solution. To build on Gazler's solution using I18n.js (which we use with our project at work), I just used a very simple Handlebars helper to facilitate the process to do the localization on the fly:

Handler

Handlebars.registerHelper('I18n',
  function(str){
    return (I18n != undefined ? I18n.t(str) : str);
  }
);

Template

<script id="my_template" type="x-handlebars-template">
    <div>{{I18n myVar}}</div>
</script>

The primary advantage of this is that there's no expensive pre/post processing on the entire json object. Not to mention if the incoming json has nested objects/arrays, the time spent looking for and parsing for them might get expensive if the object is huge.

Cheers!