Essentials

Accessing keys

resources with 2 keys:

{
    "key": "value of key",
    "look": {
        "deep": "value of look deep"
    }
}

sample

i18next.t('key');
// -> "value of key"

i18next.t('look.deep');
// -> "value of look deep"

Passing a default value

You can pass in a default value for cases the key could not be found in translations like:

i18next.t('key', 'default value to show');

In case you're using the saveMissing functionality, it will also pass the defaultValue to your chosen backend, like shown in this React.js example.

Accessing keys in different namespaces

Namespaces are a feature in i18next internationalization framework which allows you to separate translations that get loaded into multiple files.

init

i18next.init({
  ns: ['common', 'moduleA'],
  defaultNS: 'moduleA'
});

moduleA.json

{
    "name": "Module A"
}

common.json

{
    "button": {
        "save": "save"
    }
}

sample

i18next.t('name');
// -> "Module A"

// from different namespace (not recommended with namespace prefix when used in combination with natural language keys)
i18next.t('common:button.save') // -> "save"
// better use the ns option:
i18next.t('button.save', { ns: 'common' }) // -> "save"

Multiple fallback keys

Calling the t function with an array of keys enables you to translate dynamic keys providing a non specific fallback value.

As a sample think of an error code you get and you like to show a specific warning in some cases:

keys

{
  "error": {
    "unspecific": "Something went wrong.",
    "404": "The page was not found."
  }
}

sample

// const error = '404';
i18next.t([`error.${error}`, 'error.unspecific']); // -> "The page was not found"

// const error = '502';
i18next.t([`error.${error}`, 'error.unspecific']); // -> "Something went wrong"

Overview options

i18next.t(key, options)

Last updated