0
votes

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

1 Answers

0
votes

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