Skip to content

onepercentclub/ember-i18next

 
 

Repository files navigation

Ember-i18next Build Status

About

An Ember CLI addon for internationalizing Ember.js applications using the i18next library. The addon provides an Ember service that wraps i18next and a Handlebars helper for displaying localized text in templates.

Ember-i18next 2.0 only supports Ember.js 1.13 and higher.

Installation

To install with Ember CLI >= 0.2.3:

ember install ember-i18next

To install with Ember CLI 0.1.5 - 0.2.2:

ember install:addon ember-i18next

For older versions:

npm install --save-dev ember-i18next
bower install --save i18next

Upgrading from ember-i18next 1.X

To upgrade from ember-i18next 1.X, you will need to update the i18next dependency in bower.json and add a dependency for the i18next XHR resource loader.

"dependencies": {
  "i18next": "^3.3.1",
  "i18next-xhr-backend": "^0.6.0"
}

You should review your i18next configuration in environment.js, particularly if you have translations with interpolated values. The default interpolation prefix and suffix have changed to {{/}}, necessitating changes to your JSON files or configuration changes. See the i18next documentation for interpolation options and the section of the migration guide on running with compatibility flags.

Configuration

Configuring i18next

To configure the i18next options and the XHR backend options, add them to your environment.js:

// ...
var ENV = {
  // ...
  i18nextOptions: {
    // any options supported by i18next
    backend: {
      // any options supported by i18next-xhr-backend
    }
  },
  APP: {
    // ...
  }
}

If you do not specify any options, the default i18next options will be used.

Initializing i18next

To initialize the i18next library, call the i18n service's initLibraryAsync method. This method returns a promise that resolves when the library finishes initializing, so if you call it in one of the model hook methods (beforeModel, model, afterModel), the application will enter the loading substate until i18next is initialized.

Including Locale Files

By default, i18next loads locale files from the server asynchronously from the server path configured using the resGetPath configuration option. To copy your application's locale resources from your source tree to the expected path during build, modify the application's ember-cli-build.js (Brocfile.js in earlier versions of ember-cli):

/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
var funnel = require('broccoli-funnel');

module.exports = function(defaults) {
  var app = new EmberApp();

  var locales = funnel('app/locales', {
    srcDir: '/',
    destDir:  '/locales'
  });

  // other configuration, app.import() calls, etc. ...

  return app.toTree(locales);
}

In this example, locale files are recursively copied from the application's app/locales/ directory to dist/locales/ when the application is built.

Use

Service

If you need to produce translated strings in routes, components or controllers, you can inject the i18n service using the Ember.inject API. This will then give access to i18next's t() function in your code. For example:

// app/components/example-component.js
import Ember from 'ember';

export default Ember.Component.extend({
  i18n: Ember.inject.service(),
  messages: someObject,

  messageCount: Ember.computed('messages', function () {
    const i18n = this.get('i18n');
    const count = this.get('messages.count');
    return i18n.t('messages.count', { msgCount: count });
  }
});

For convenience, a mixin is provided that injects the i18n service and adds a t() function to the including class. For example, the above could be accomplished using the mixin like this:

// app/components/example-component.js
import Ember from 'ember';
import I18nMixin from 'mixins/i18n';

export default Ember.Component.extend(I18nMixin, {
  messages: someObject,

  messageCount: Ember.computed('messages', function () {
    const count = this.get('messages.count');
    return this.t('messages.count', { msgCount: count })
  });
});

Handlebars Helper

You can access your app's translations in templates using the t helper:

<button type="button">{{t 'button.text'}}</button>

Pass values to be interpolated into the translation as hash arguments. For example, for a translation that includes an interpolated {{count}} value:

<div>{{t 'messages.count' count=3}}</div>

Current Locale

The current locale is exposed via a locale property added to the i18n service. To change the language that the appliction is displayed in, simply set this property, and all of the text displayed using the t helper will be updated. For example, triggering the following controller action would update all of the text to Thai:

// app/controllers/example-controller.js
import Ember from 'ember';

export default Ember.Controller.extend(I18nMixin, {
  actions: {
    gimmeThai() {
      this.set('i18n.locale', 'th-TH');
    }
  }
});

Pre- and Post-Init Actions

Changing the locale causes i18next to be reinitialized, which can destroy state. For example, if you have used addResources to load additional localization strings, they will be lost during initialization. To handle management of state around library initialization, you can register actions to perform before and after library initialization with the i18n service using the registerPreInitAction and registerPostInitAction methods.

import Ember from 'ember';
import I18nMixin from '../mixins/i18n';

export default Ember.Route.extend(I18nMixin, {
  init() {
    this._super();
    const i18n = this.get('i18n');

    // my-fancy-action is a name that can be used to unregister the action later
    i18n.registerPostInitAction('my-fancy-action', oldLang => {
      // do preloading
    });
  }
}

Pre- or post-init actions may return a promise. If any of the actions returns a promise, the service will wait for the promises to resolve before moving on. If pre-init actions return promises, the service will wait for them to resolve before initializing i18next. If post-init actions return promises, the service will wait for them to resolve before notifying the application about the change in locale.

The new locale is passed as a parameter to pre-init actions and the old locale to post-init actions. These parameters are undefined when the the i18n service's initLibraryAsync method is called.

Finally, actions may be unregistered using the unregisterPreInitAction and unregisterPostInitAction methods. To unregister the post-init action from the previous example, you would do the following:

// ...
i18n.unregisterPostInitAction('my-fancy-action');
// ...

Testing

Acceptance Tests

No special configuration is required for acceptance testing, although it may be convenient to configure the default locale and preload locales for use in the tests. For example:

// in environment.js
if (environment === 'test') {
  // ...
  ENV.i18nextOptions.lng = 'en-us';
  ENV.i18nextOptions.preload = ['en-us', 'th-th'];
}

Component Integration Tests

If you need to make assertions about the text rendered in component integration tests, you can initialize the i18n service in a beforeEach hook.

moduleForComponent('some-component', 'Integration | Component | some component', {
  integration: true,

  beforeEach(assert) {
    const done = assert.async();
    this.inject.service('i18n');
    this.get('i18n').initLibraryAsync().then(done);
  }
});

Alternatively, the ember-i18n-test-helpers addon is easy to use and also works well with ember-i18next.

Unit Tests

Unit tests for objects that inject the i18n service or use the {{t}} helper should add them to the needs array.

moduleForComponent('other-component', 'Unit | Component | other component', {
  unit: true,
  needs: ['service:i18n', 'helper:t'],
});

Collaborating

Contributions are happily accepted. Make sure that your pull request includes tests and your JavaScript source is styled as described in the Ember.js JavaScript style guide.

Acknowledgements

Early versions of this addon were strongly influenced by the ember-cli-i18n addon.

About

Integrates i18next into Ember CLI apps.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 92.1%
  • HTML 7.8%
  • CSS 0.1%