mardi 1 novembre 2016

Use current language when resolving a template name in Ember JS

I would like to have localized templates (similar to the behavior we get in rails) so if a template with a suffix with the current locale is found, then it's used.

Let's say that the current locale is en-us, then the template resolved for should be in order:

  • -header-en-us.hbs
  • -header-en.hbs
  • -header.hbs

I have tried to inject intl (from ember-intl) but it fails because obviously a service cannot be injected in an object whose purpose is resolving injections....

Error:

"Assertion Failed: Attempting to lookup an injected property on an object without a container, ensure that the object was instantiated via a container."

Attempt to configure the resolver:

import Ember from 'ember';
import Resolver from 'ember-resolver';

export default Resolver.extend({
  intl: Ember.inject.service(),

  resolveTemplate: function(parsedName) {
    let locale = this.get('intl').locale;

    while (locale.length) {
      let suffixed = `${parsedName}-${locale}`;
      let found = this._super(suffixed);
      if (found) {
        return found
      }
      locale = locale.split('-');
      locale.pop();
      locale = locale.join('-');
    }

    return this._super(parsedName);
  }
});




Aucun commentaire:

Enregistrer un commentaire