如何用I18n.js翻译动态键 [英] How to translate a dynamic key with I18n.js

查看:1056
本文介绍了如何用I18n.js翻译动态键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用Ember实现多语言Web应用程序时,我需要使用将被转换为用户选择语言的字符串。对于Ember,I18n.js就是这样做的。它提供了一个Handlebars帮助器,它使用一个关键字符串并处理翻译:{{t login.username}}将查找密钥login.username并将其替换为当前语言的相应文本。
我的问题是这个帮助器需要一个文字字符串值,并使用该值进行查找,但我在某些地方引用了一个字符串。例如,我使用{{#each}}表达式循环了一组哈希值,然后我必须从每个哈希值转换一个值。我想提供给翻译Handlebars助手是一个表达式,必须在当前上下文中进行评估,以确定翻译键。不幸的是,I18n.js提供的帮助不支持。
如何使用表达式而不是文字来使用I18n.js功能?

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?

推荐答案

由Handlebars助手提供I18n.js使用函数I18n.t(key,options)进行真正的翻译。
您可以编写自己的使用此功能的帮助器。这是一个不支持'options'参数的示例实现。

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);
});

然后可以在Handlebars表达式中使用:

This can then be used in a Handlebars expression:

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

这篇关于如何用I18n.js翻译动态键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆