Question

I am currently using jamesarosen/ember-i18n for internalization support on my ember 1.5.1 app.

I have two languages. English and French.

Em.I18n.translations = {
  en: {
    animal: {
      cat: 'cat',
      dog: 'dog'
    }
  },

  fr: {
    animal: {
      cat: 'chat',
      dog: 'chien'
    }
  }
};

In my handlebars template I have: -

{{t animal.cat}}

However I get the message:

Missing translation: animal.cat.

It would work if I place:

{{t en.animal.cat}} or {{t fr.animal.cat}}

What is the best practice to get this working and to make it automatically switchable between the two languages? I have tried setting this at the top of my file:

Em.I18n.locale = 'fr';
Était-ce utile?

La solution

I found the answer to this:

Adding this helper:

Ember.Handlebars.registerHelper('i18n', function(property, options) {
  var params = options.hash,
      self = this;

  // Support variable interpolation for our string
  Object.keys(params).forEach(function (key) {
    params[key] = Em.Handlebars.get(self, params[key], options);
  });

  property = Em.I18n.locale + '.' + property;

  return Em.I18n.t(property, params);
});

And making sure this is set:

Em.I18n.locale = 'en';

Using the updated handlebars reference:

{{i18n animal.cat}}

Autres conseils

@Tom's solution is good but would only work for the helpers.

More generally, if you want to use e.g. Em.I18n.TranslateableProperties, you would have to handle them separately.

In my opinion, the whole content of Em.I18n.translations could be changed once you want to change locale.

That would require refresh of the page as you didn't set any listeners on Ember.I18n.locale. It is possible to do it dynamically but it gets a bit more complicated.

Apart from that, the best option would be probably to have the translations coming from the backend side.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top