How is internationalization configured for Hogan.js?

后端 未结 2 1730
名媛妹妹
名媛妹妹 2021-01-20 15:31

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

相关标签:
2条回答
  • 2021-01-20 15:54

    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?).

    0 讨论(0)
  • 2021-01-20 16:07

    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.

    0 讨论(0)
提交回复
热议问题