Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make client side I18n with mustache.js

i have some static html files and want to change the static text inside with client side modification through mustache.js.

it seems that this was possible Twitter's mustache extension on github: https://github.com/bcherry/mustache.js

But lately the specific I18n extension has been removed or changed.

I imagine a solution where http:/server/static.html?lang=en loads mustache.js and a language JSON file based on the lang param data_en.json.

Then mustache replaces the {{tags}} with the data sent.

Can someone give me an example how to do this?

like image 589
mancereus Avatar asked Mar 22 '11 10:03

mancereus


2 Answers

You can use lambdas along with some library like i18next or something else.

{{#i18n}}greeting{{/i18n}} {{name}}

And the data passed:

{
    name: 'Mike',
    i18n: function() {
        return function(text, render) {
            return render(i18n.t(text));
        };
    }
}

This solved the problem for me

like image 64
categulario Avatar answered Oct 12 '22 23:10

categulario


I don't think Silent's answer really solves/explains the problem.

The real issue is you need to run Mustache twice (or use something else and then Mustache).

That is most i18n works as two step process like the following:

  1. Render the i18n text with the given variables.
  2. Render the HTML with the post rendered i18n text.

Option 1: Use Mustache partials

<p>{{> i18n.title}}</p>
{{#somelist}}{{> i18n.item}}{{/somelist}}

The data given to this mustache template might be:

{ 
  "amount" : 10, 
  "somelist" : [ "description" : "poop" ]
}

Then you would store all your i18n templates/messages as a massive JSON object of mustache templates on the server:

Below is the "en" translations:

{ 
   "title" : "You have {{amount}} fart(s) left", 
   "item" : "Smells like {{description}}"
}

Now there is a rather big problem with this approach in that Mustache has no logic so handling things like pluralization gets messy. The other issue is that performance might be bad doing so many partial loads (maybe not).

Option 2: Let the Server's i18n do the work.

Another option is to let the server do the first pass of expansion (step 1). Java does have lots of options for i18n expansion I assume other languages do as well.

Whats rather annoying about this solution is that you will have to load your model twice. Once with the regular model and second time with the expanded i18n templates. This is rather annoying as you will have to know exactly which i18n expansions/templates to expand and put in the model (otherwise you would have to expand all the i18n templates). In other words your going to get some nice violations of DRY.

One way around the previous problem is pre-processing the mustache templates.

like image 31
Adam Gent Avatar answered Oct 12 '22 23:10

Adam Gent