How to do advanced i18n with Mustache.js?

dani picture dani · Nov 8, 2011 · Viewed 7.9k times · Source

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.

Answer

martin picture martin · Mar 7, 2012

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 :)