How to translate a dynamic key with I18n.js

左心房为你撑大大i 提交于 2020-02-07 05:34:26

问题


While implementing a multi language web application with Ember I had the need to use strings that would be translated to the language of the user's choice. For Ember there is I18n.js that does just that. It provides a Handlebars helper that takes a key string and handles the translation: {{t login.username }} would lookup the key "login.username" and replace it with the current language's corresponding text. My problem is that this helper takes a literal string value and does the lookup with that value, but I have in some places a reference to a string. For instance, I'm looping over an array of hashes with an {{#each}} expression and then I would have to translate a value from each hash. What I would like to supply to the translation Handlebars helper is an expression that would have to be evaluated in the current context in order to determine the translation key. Unfortunately the helper provided by I18n.js does not support that. How can I use I18n.js functionality with an expression instead of a literal?


回答1:


The Handlebars helper provided by I18n.js uses a function I18n.t(key, options) to do the real translation. You can write your own helper that uses this same function. Here is an example implementation that does not support the 'options' parameter.

Em.Handlebars.registerHelper('translate', function(keypath, options) {
    var translationKey = Em.Handlebars.get (this, keypath, options);
    return Em.I18n.t(translationKey);
});

This can then be used in a Handlebars expression:

{{#each type in dishtypes}}
{{translate type.key}}
{{/each}}


来源:https://stackoverflow.com/questions/18072955/how-to-translate-a-dynamic-key-with-i18n-js

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