Interpolation

Interpolation is one of the most used functionalities in I18N. It allows integrating dynamic values into your translations.

Per default, interpolation values get escaped to mitigate XSS attacks.

🎓 Check out this topic in the i18next crash course video.

If the interpolation functionality provided doesn't suit you, you can use i18next-sprintf-postProcessor for sprintf supported interpolation.

Basic

Interpolation is one of the most used functionalities in I18N.

Keys

Keys, by default, are strings surrounded by curly brackets:

{
    "key": "{{what}} is {{how}}"
}

Sample

i18next.t('key', { what: 'i18next', how: 'great' });
// -> "i18next is great"

Working with data models

You can also pass entire data models as a value for interpolation.

Keys

{
    "key": "I am {{author.name}}"
}

Sample

const author = { 
    name: 'Jan',
    github: 'jamuhl'
};
i18next.t('key', { author });
// -> "I am Jan"

Unescape

By default, the values get escaped to mitigate XSS attacks. You can toggle escaping off, by either putting - before the key, or set the escapeValue option to false when requesting a translation.

Keys

{
    "keyEscaped": "no danger {{myVar}}",
    "keyUnescaped": "dangerous {{- myVar}}"
}

Sample

i18next.t('keyEscaped', { myVar: '<img />' });
// -> "no danger &lt;img &#x2F;&gt;"

i18next.t('keyUnescaped', { myVar: '<img />' });
// -> "dangerous <img />"

i18next.t('keyEscaped', { myVar: '<img />', interpolation: { escapeValue: false } });
// -> "no danger <img />" (obviously could be dangerous)

Warning: If you toggle escaping off, escape any user input yourself!

Additional options

Prefix/Suffix for interpolation and other options can be overridden in the init options or by passing additional options to the t function:

i18next.init({
    interpolation: { ... }
});

i18next.t('key', {
    interpolation: { ... }
});

While there are a lot of options going with the defaults should get you covered.

All interpolation options

Implications for localization

Checkout the best practices on this topic.

Last updated