I18next: Use same resource for same language but different IETF language tag

Created on 10 Sep 2019  路  5Comments  路  Source: i18next/i18next

Hi! I have the following code:

import i18n from 'i18next'

import { initReactI18next } from 'react-i18next'
import locales from 'locales'

const resources = {
  en: locales.en,
  no: locales.no,
  de: locales.de,
  se: locales.se
}

function getDefaultLocale() {
  const preferredLanguage = localStorage.getItem('preferredLanguage')
  const lng = locales.languages
    .map(({ code }) => code)
    .find(code =>
      code === preferredLanguage || // The user has set a preferred language
        code === '__DEFAULT_LOCALE__' || // Default locale set at build time.
        code === navigator.language
    )
  return lng
}

i18n
  .use(initReactI18next)
  .init({
    resources,
    lng: getDefaultLocale(),
    appendNamespaceToCIMode: true
  })

export default i18n

My problem is, that let's say when the English language is detected with navigator.language, it may be en, en-US, en-GB, or for Norwegian, it may be nb, nb-NO, ny-NO etc.

We would like to serve the same translations for all English language codes, and the same for all the Norwegian language codes.

My current solution is to defined resources like so:

const resources = {
  en: locales.en,
  'en-US': locales.en,
  'en-GB': locales.en,
  no: locales.no,
  'nb-NO': locales.no,
  'ny-NO': locales.no,
  de: locales.de,
  se: locales.se
}

But there must be a better solution to this! Could someone help?

All 5 comments

did you actually test if your setup not already works? https://www.i18next.com/principles/fallback#language-fallback i18next already does a lookup en-US -> en

@jamuhl, English does seem to work, but not Norwegian.navigator.language yields nb, and it does not fall back to no.
With fallbackLanguage, I have to do something like this, I guess(?):

//...
fallbackLng: {
  nb: ['no'],
  nn: ['no'],
  'nb-NO': ['no'],
  'nn-NO': ['no'],
  'se-NO': ['no'],
  default: ['en']
}, //...

If I understand it correctly, the property name is the user's language, and the value is which language to fall back to. Right? Wouldn't it be more meaningful to swap them? So one could do something like:

//...
no: ["nb", "nb-NO", "nn", "nn-NO", "se-NO"]
//...

Saying "these languages listed in the value, should fall back to the language defined with the property name".

no is a country (region) not a language...language is either nn (nynorsk) or nb (bokmal)...there is no no nor se-NO

at least not official in the browser ;)

Of course! 馃檲Thank you for the (obvious) answer.

But then it means my best option is as in my previous comment, define ['no'] as fallback for all the languages nb-NO etc.?

yes...if you like to fallback that way...

Was this page helpful?
0 / 5 - 0 ratings