c4-8ka
Last Updated: February 25, 2016
·
1.932K
· manufaktor

Ember.js translations with bindings

I wanted to create a Rails style translation helper for my views, but the ember guides do not show how to create a helper that is bound to anything else than the value you pass it.

App = Ember.Application.create({i18n: Ember.Object.create({})});

# This could be a model in your application route...
Ember.$.getJSON("/translations").then(function(translations){
    App.set("i18n", translations);
});

# create the view, which we'll bind to App.get("i18n")
var I18nTextView = Ember.View.extend({
  tagName: "span",
  template: Ember.Handlebars.compile("{{view.translatedContent}}"),

  translatedContent: (function() {
    return this.get("content").get(this.get("value"));
  }).property("content")
});

Ember.Handlebars.registerHelper("i18n", function(i18nKey, options) {
  options.hash.contentBinding = "App.i18n";
  options.hash.value = i18nKey
  return Ember.Handlebars.helpers.view.call(this, I18nTextView, options);
});

Now everytime you update App.set("i18n"), all translations will be updated.
In your view, simply use:

<div class="i18n-demo">
  {{i18n "my.scoped.translation.key"}}
</div>

You can further extend this to add styles to the span and highlight missing translations.