cyclomarc
cyclomarc

Reputation: 2012

Ember: how to use i18n translations in controller code?

I am using Ember i18n in my app. I also want to use the translation strings in the controllers (in most cases in an alert or confirm message). How can this be done ?

See http://jsfiddle.net/cyclomarc/36VS3/2/

Clicking on the button should alert "info" and not "T1005" ...

<script type="text/x-handlebars">
    {{t T1005}}<br>
    <button {{action 'clickMe' content}}>{{t T1005}} - Click me</button>
</script>

CLDR.defaultLanguage = 'en';

App.ApplicationController = Ember.Controller.extend({
    clickMe: function(){
        alert('T1005');
    }
})

I know that a possible workaround is to no longer use alert and confirm and replace them by for example the bootstrap alternatives. However, I could imagine that in certain cases you will want to do something with the strings in Javascript (e.g. update a certain label via jQuery or so).

Any ideas on how to use the i18n strings in the controllers is helpful. Using an i18n library is only usefull if all aspects of the application can be translated ...

Upvotes: 2

Views: 1923

Answers (4)

crusy
crusy

Reputation: 1512

The answer from cyclomarc didn't work for me (it's from 2013, which might be related), but it pointed me in the right direction:

this.container.lookup('service:i18n').t('my.translation.id')

Upvotes: 0

Pierrot
Pierrot

Reputation: 1

The solution that works to me is the following (using Ember I18n):

App.ApplicationController = Ember.Controller.extend(Em.I18n.translateableProperties, {
  messageTranslation: 'T001',

  showMessage: function(){
    alert(this.get('message'));
  }
});

Upvotes: 0

Manumie
Manumie

Reputation: 156

Might be late here, but what about using the Em.I18n.TranslateableProperties mixin as documented here ?

You could do something like :

App.ApplicationController = Ember.Controller.extend(Em.I18n.translateableProperties, {
    messageTranslation: 'T1005',

    clickMe: function(){
        alert(this.get('message'));
    }
});

In the template, {{message}} will also hold the translation.

Upvotes: 1

cyclomarc
cyclomarc

Reputation: 2012

Just found the solution. Just access the string via Ember.I18n.t("T1005");

JSFiddle updated: http://jsfiddle.net/cyclomarc/36VS3/7/

Upvotes: 4

Related Questions