How to make client side I18n with mustache.js

后端 未结 5 1634
北荒
北荒 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:36

    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

    {{> i18n.title}}

    {{#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.

提交回复
热议问题