Search code examples
ember.jsember-cli

Internationalization of ember application


I'm using ember-i18n lib for Internationalisation and want to save current locale in route like:

domain.com - empty for default en

doman.com/es, doman.com/de- for another

For this I tried to use rootURL

Router.reopen({
  rootURL: '/' ('es' or 'de')
});

Problem: When rootURL is not empty, app can't redirect and fail with error: ember.debug.js:4903 Uncaught Error: Assertion Failed: Path / does not start with the provided rootURL /es/

Question: What is the best solution to make redirect, all logic will be hold in emebr so I can't move this logic into nginx and etc.

Another option is Make a wrapper route, looks like this:

this.route(
    'lang', { path: '/:lang' }, function (){..}
);

This solution looks like not good:

  1. link-to helper will require lang param
  2. lang can't be empty (for default language)

UPDATE: I understand how to dynamic change rootURL, but can't auto redirect.


Solution

  • Found the solution, describe this logic in instance-initializer

        export function initialize(app) {
      var router = app.lookup('router:main');
      var i18n = app.lookup('service:i18n');
    
      var path = window.location.pathname;
      var currentLang = ENV.i18n.defaultLocale;
      var newPath = '';
    
      var LangFromPath = path.match('^/([a-z]{2})(?:/|$)');
      if (LangFromPath && LangFromPath[1]){
        currentLang = (ENV.i18n.allowedLocales.indexOf(LangFromPath[1]) > -1) ? LangFromPath[1] : currentLang;
      }
    
      if (currentLang != ENV.i18n.defaultLocale) {
        var newPath = '/' + currentLang + '/';
      }
    
      router.rootURL = newPath;
      i18n.set('locale', currentLang);
    
      if (newPath && path.indexOf(newPath) === -1) {
          window.location.pathname = newPath;
      }
    
    }