Migrating from ember-i18n to ember-intl


#1

I decided to migrate from deprecated ember-i18 to a new ember-intl. After transforming the old translation files with a provided migrator, I’m still stuck with initialization of the locale. Previously, I used an initializer i18n.js defined in app/initializers folder as follows:

export default {
  name: 'i18n',

  after: 'ember-i18n',

  initialize: function(app) {
    app.inject('model', 'i18n', 'service:i18n');
    app.inject('controller', 'i18n', 'service:i18n');
    app.inject('route', 'i18n', 'service:i18n');
  }
};

and I set up the default locale based on the User browser settings in app/instance-initializers/i18n.js as follows:

export function initialize(applicationInstance) {
  let i18n = applicationInstance.lookup('service:i18n');
  let moment = applicationInstance.lookup('service:moment');
  let locale = calculateLocale(i18n.get('locales'));
  i18n.set('locale', locale);
  moment.setLocale(locale);
}

function calculateLocale(locales) {
  // whatever you do to pick a locale for the user:
  const language = navigator.languages[0] || navigator.language || navigator.userLanguage;

  return  locales.includes(language.toLowerCase()) ? language : 'en-GB';
}

export default {
  name: 'i18n',
  initialize
};

Unfortunately, ember-intl is missing clear docs explaining how to do that. Do you have any ideas or tips? Thank you.


#2

Finally, I figured out how to solve it :slight_smile:

  1. As suggested, I get a browser’s locale and set it in beforeModel hook of application route:
#routes/application.js

import { inject as service } from '@ember/service';
import Route from '@ember/routing/route';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
import moment from 'moment';

export default Route.extend(ApplicationRouteMixin, {
  currentUser: service(),
  intl: service(),
  constants: service(),

  beforeModel() {
    let locale = this.figureOutLocale();
    this.intl.setLocale(locale);
    moment.locale(locale);
    return this._loadCurrentUser();
  },
...
  figureOutLocale() {
    let locale = this.calculateLocale(this.intl.get('locales'));
    return locale;
  },

  calculateLocale(locales) {
    const language = navigator.languages[0] || navigator.language || navigator.userLanguage;

    return  locales.includes(language.toLowerCase()) ? language : 'en-US';
  }
});
  1. Then I used the migrator provided by DocYard to migrate from ember-18n to ember-intl.

Hope this helps


#3

Thanks! We also started using ember-intl and love the way you can create the language .yaml files from one .yaml file with this tool: https://www.codeandweb.com/babeledit/tutorials/how-to-translate-your-ember-app-with-ember-intl

See the result: https://www.martinic.com/ar


#4

@broerse Thank you very much, really appreciated for such a detailed example with real use cases! Special thanks for the link to BabelEdit, - I’ve never heard about this tool. Really cool.