Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 660
mdcarter Avatar asked Oct 13 '11 20:10

mdcarter


People also ask

How do you add templates in your HTML in handlebars?

Templates The recommended way of adding templates to your page is by including them in <script> tags with a special type. The type attribute is important, otherwise the browser will attempt to parse them as JavaScript (which they are not). The templates have an easy to grasp syntax.

How do I compile handlebars templates?

Precompiling Templates Inside NodeJS If you wish to precompile templates from inside NodeJS--without invoking "handlebars" from the command line--that can be done with Handlebars. precompile. Transmit the string result of this function to your clients, and they can in turn parse that with Handlebars. template.

How do you use JavaScript handlebars?

Define the template that is packed with handlebars JavaScript syntax. Compile the template with handlebars JavaScript compile method. Provide the data context i.e. data from server-side in a form of JSON to map to the template. Insert or append the final HTML into your designated DOM location of the HTML page.

How handlebars js is different from mustache js?

Handlebars. js is an extension to the Mustache templating language created by Chris Wanstrath. Handlebars. js and Mustache are both logicless templating languages that keep the view and the code separated like we all know they should be; Mustache: Logic-less templates.


1 Answers

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!

like image 54
poweratom Avatar answered Sep 28 '22 21:09

poweratom