How is internationalization configured for Hogan.js?

混江龙づ霸主 提交于 2019-12-31 02:03:43

问题


I'm looking to use hogan.js to create html form a template in the browser. I've read that hogan supports i18n, but I can't find an example of how this works. How do you pass the translated text to hogan and what tag do you put in the template, I have seen both {{_i}} and {{i18n}}?


回答1:


It would seem I was confusing an older fork of Mustache.js from Twitter, with Hogan a separate mustache compiler from also from twitter. The fork does support an {{_i}} tag for internationalization. This will then call a global function with the name _ in which you provide you're own method for looking up the translated value. E.g.

translatedStrings = {
   name: "Nom";
}

function _(i18nKey) {
   return translatedStrings[i18nKey];
}

var template = "{{_i}}Name{{/i}}: {{username}}",
    context = {username: "Jean Luc"};

Mustache.to_html(template, context);

Would return "Nom: Jean Luc". Whereas with Hogan internationalization is achieved with normal mustache lambdas, e.g.:

translatedStrings = {
   name: "Nom";
}

var template = "{{#i18n}}Name{{/i18n}}: {{username}}",
    context = {
       username: "Jean Luc",
       i18n: function (i18nKey) {return translatedStrings[i18nKey];}
    };

Hogan.compile(template).render(context);

See http://mustache.github.com/mustache.5.html for more on providing lambdas. So the main distinction is that the function to look up translations must always be provided on the context when rendering with Hogan, whereas the mustache fork will look up a global method.




回答2:


It is actually easy to combine this with other internationalisation approaches. We are using jquery-i18n-properties, which is a jQuery plugin that supports the use of .properties files, which are compatible to Java.

The framework tries to download a file called Messages.properties and depending on the browsers language fo example Messages_en.properties and Messages_en_US.properties. This allows to build a hierarchy of translations very quickly.

So slightly changing the example of slashnick and using hogan/mustache, I write:

var template = "{{#i18n}}Name{{/i18n}}: {{username}}",
    context = {
       username: "Jean Luc",
       i18n: function (i18nKey) {return jQuery.i18n.prop(key);}
    };

 // Init i18n
jQuery.i18n.properties(
{
name:'Messages', 
path:'some/path',
mode : 'map'
});

Hogan.compile(template).render(context);

Messages.properties File:

Name = Name

Messages_fr.properties File:

Name = nom

I do not really see the advantage of using the special mustache version with looks up a global function (performance maybe?).



来源:https://stackoverflow.com/questions/9211217/how-is-internationalization-configured-for-hogan-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!