Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with detecting browser language and using it with i18next

I'm working on a webapp. I'm using i18next and it doesn't detect language unless I specify "lng" on options. If I use "navigator.language || navigator.userLanguage" and it's OK with Chrome. It returns something like "en". But Firefox for example, returns "en-GB". I don't use regional translation and i18next doesn't redirect "en-GB" to "en". So, system doesn't work.

Here is my code:

$(document).ready(function(){
      i18next.use(i18nextXHRBackend);
      i18next.init({
          'debug': true,
          'lng': navigator.language || navigator.userLanguage,
          'fallbackLng': 'en',
          'load': 'currentOnly',
          'backend': {
            loadPath: 'locales/{{lng}}/{{ns}}.json'
          }
      }, function() {
          jqueryI18next.init(i18next, $);
          $('body').localize();
      });
    });
like image 974
mutlucan96 Avatar asked Jul 22 '16 17:07

mutlucan96


People also ask

How does i18next detect language?

detectLanguage() Detects the language of the provided text using the Compact Language Detector (CLD). This is an asynchronous function that returns a Promise .

What is i18next?

i18next is an internationalization-framework written in and for JavaScript. But it's much more than that! i18next goes beyond just providing the standard i18n features such as (plurals, context, interpolation, format). It provides you with a complete solution to localize your product from web to mobile and desktop.


1 Answers

i18next supports region languages...that's what localization is about.

if you like to support only languages without region set load: 'languageOnly':

$(document).ready(function(){
  i18next.use(i18nextXHRBackend);
  i18next.init({
      'debug': true,
      'load': 'languageOnly',
      'lng': navigator.language || navigator.userLanguage,
      'fallbackLng': 'en',
      'load': 'currentOnly',
      'backend': {
        loadPath: 'locales/{{lng}}/{{ns}}.json'
      }
  }, function() {
      jqueryI18next.init(i18next, $);
      $('body').localize();
  });
});

this will avoid accepting en-GB for lookups and only use en. Without setting this i18next will still output same result but also try to load en-GB translations.

like image 146
jamuhl Avatar answered Sep 22 '22 15:09

jamuhl