Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do advanced i18n with Mustache.js?

It seems Twitter is using a fork of Mustache.js to provide i18n to its templates?

Could someone give a brief example of how this is done and perhaps also outline what semantics is necessary to crowdsource these translations?

There is of course this simple example:

var template = "{{_i}}{{name}} is using mustache.js!{{/i}}"

var view = {
  name: "Matt"
};

var translationTable = {
  // Welsh, according to Google Translate
  "{{name}} is using mustache.js!": "Mae {{name}} yn defnyddio mustache.js!"
};

function _(text) {
  return translationTable[text] || text;
}

alert(Mustache.to_html(template, view));
// alerts "Mae Matt yn defnyddio mustache.js!"

But I'd like some more insight on how to structure the _(text) function and translationTable to provide conditionals, singular, plural etc. Examples of solving more advanced use cases would be much appreciated.

like image 338
dani Avatar asked Nov 08 '11 13:11

dani


2 Answers

I know i'm not answering your question really, but unless you are planning on spending a lot of time on this project I would seriously consider just leaving this as a data issue.

{
    title : {
        key: 'título',
        value: 'bienvenida'
    }
}

And:

{
    title : {
        key: 'لقب',
        value: 'ترحيب'
    }
}

Then just make the template generic:

<h1>{{title.key}}: {{title.value}}</h1>

And:

<h1>{{title.value}} {{title.key}}</h1>

All you need to maintain is a 1:1 mapping between templates and data.

Mustache.render(data[language], template[language]);

Keep it simple :)

like image 109
martin Avatar answered Nov 08 '22 12:11

martin


Structuring the more advanced cases including conditionals, loops and so on are done in the exact same way as with the regular Mustache library. You can use the new I18N {{_i}} start and {{/i}} end tags to wrap parts of your template for translation purposes.

If you template is:

<h1>Title: {{title}}</h1>
<ul>
   {{#a_list}}
      <li>{{label}}</li>
   {{/a_list}}
</ul>

you can just wrap the first line

<h1>{{_i}}Title: {{title}}{{/i}}</h1>

and include the inner part in the translation map.

See http://jsfiddle.net/ZsqYG/2/ for a complete example.

like image 39
Ryan953 Avatar answered Nov 08 '22 12:11

Ryan953