How to make client side I18n with mustache.js

后端 未结 5 1642
北荒
北荒 2021-02-08 21:11

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 mu

5条回答
  •  忘了有多久
    2021-02-08 21:28

    My answer is based on developingo's. He's answer is very great I'll just add the possibility to use mustache tags in the message keycode. It is really needed if you want to be able the get messages according to the current mustache state or in loops

    It's base on a simple double rendering

     info.i18n = function(){
            return function(text, render){
                var code = render(text); //Render first to get all variable name codes set
                var value = i18n.t(code)
                return render(value); //then render the messages
            }
        }
    

    Thus performances aren't hit because of mustache operating on a very small string.

    Here a little example :

    Json data :

     array : 
        [
            { name : "banana"},
            { name : "cucomber" }
        ]
    

    Mustache template :

    {{#array}}
        {{#i18n}}description_{{name}}{{/i18n}}
    {{/array}}
    

    Messages

    description_banana = "{{name}} is yellow"
    description_cucomber = "{{name}} is green"
    

    The result is :

    banana is yellow
    cucomber is green
    

    Plurals

    [Edit] : As asked in the comment follows an example with pseudo-code of plural handling for english and french language. Its a very simple and not tested example but it gives you a hint.

    description_banana = "{{#plurable}}a {{name}} is{{/plurable}} green" (Adjectives not getting "s" in plurals)
    
    description_banana = "{{#plurable}}Une {{name}} est verte{{/plurable}}" (Adjectives getting an "s" in plural, so englobing the adjective as well)
    
    info.plurable = function() 
    {
      //Check if needs plural
      //Parse each word with a space separation
      //Add an s at the end of each word except ones from a map of common exceptions such as "a"=>"/*nothing*/", "is"=>"are" and for french "est"=>"sont", "une" => "des"
      //This map/function is specific to each language and should be expanded at need.
    }
    

提交回复
热议问题