How to make i18n with Handlebars.js (mustache templates)?

后端 未结 7 2134
予麋鹿
予麋鹿 2021-01-30 00:30

I\'m currently using Handlebars.js (associated with Backbone and jQuery) to make a web app almost totally client side rendered, and I\'m having issues with the internationalisat

7条回答
  •  暖寄归人
    2021-01-30 00:39

    https://github.com/fnando/i18n-js is a ruby gem that will create an internationalization file from your config/locales folder. However if you are not using rails, you can find the javascript used on its own here.

    You then simply store the translations in a nested object..

    I18n.translations = {"en":{"date":{"formats":{"default":"%Y-%m-%d","short":"%b %d","long":"%B %d, %Y"}}}};
    

    Something that may also be of use to you that I use on my projects is a patch to mustache that automatically translates strings in the format @@translation_key@@

    i18nize = function (result) {
        if (I18n) {
          var toBeTranslated = result.match(/@@([^@]*)@@/gm);
          if (!toBeTranslated) return result;
          for(var i = 0; i < toBeTranslated.length; i++) {
            result = result.replace(toBeTranslated[i], I18n.t(toBeTranslated[i].replace(/@/g, "")));
          }
        }
        return result;
    };
    

    You then call i18nize after render to allow you to put translations in your templates instead of passing them through.

    Beware of patching mustache as you will not be able to port your templates to standard mustache implementations. However in my case, the benefits offered outweighed this issue.

    Hope this helps.

提交回复
热议问题