I18next: Use translation keys with "." in names

Created on 28 Sep 2018  路  4Comments  路  Source: i18next/i18next

I have translation keys in the following format

{
    "en": {
        "dg.userPortal.data.deleteAccount.action": "Delete account",
        "dg.userPortal.data.deleteAccount.confirmModal.action.cancel": "Cancel"
    },
    "de": {
        "dg.userPortal.data.deleteAccount.action": "Konto l枚schen",
        "dg.userPortal.data.deleteAccount.confirmModal.action.cancel": "Abbrechen"
    }
}

Is there any way I can use this with i18next. My setup below does not work:

import i18n from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';

function i18nInit() {
  return i18n.use(LanguageDetector).init({
    interpolation: {
      // React already does escaping
      escapeValue: false,
    },
    debug: true,
    fallBackLng: 'en',
    nsSeparator: '.',
    resources: {
      en: {
        'dg.userPortal.data.deleteAccount.action': 'Delete account',
        'dg.userPortal.data.deleteAccount.confirmModal.action.cancel': 'Cancel',
      },
      de: {
        'dg.userPortal.data.deleteAccount.action': 'Konto l枚schen',
        'dg.userPortal.data.deleteAccount.confirmModal.action.cancel': 'Abbrechen',
      },
    },
  });
}

export { i18nInit };

All 4 comments

import i18n from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';

function i18nInit() {
  return i18n.use(LanguageDetector).init({
    interpolation: {
      // React already does escaping
      escapeValue: false,
    },
    debug: true,
    fallBackLng: 'en',
    nsSeparator: '.',
    keySeparator: false,
    resources: {
      en: {
translation: {
        'dg.userPortal.data.deleteAccount.action': 'Delete account',
        'dg.userPortal.data.deleteAccount.confirmModal.action.cancel': 'Cancel',
}
      },
      de: {
translation: {
        'dg.userPortal.data.deleteAccount.action': 'Konto l枚schen',
        'dg.userPortal.data.deleteAccount.confirmModal.action.cancel': 'Abbrechen',
}
      },
    },
  });
}

export { i18nInit };

set keySeparator: false so you can have "flat" keys (having .) -> add at least the wrapper for default namespace (translation) around your keys

@jamuhl That doesn't work, I get the following error:

i18next::translator: missingKey en dg userPortalfalsedatafalsedeleteAccountfalseaction userPortalfalsedatafalsedeleteAccountfalseaction

ah....remove that nsSeparator option

it will take dg as namespace which would need a structure like:

en -> dg -> keys

Awesome, that works!

Was this page helpful?
0 / 5 - 0 ratings