Formatting
Starting with i18next>=21.3.0 you can use the built-in formatting functions based on the Intl API.
Starting with i18next v26.0.0, the legacy interpolation.format function will be removed. The built-in Formatter is now always used. For custom formatting, use i18next.services.formatter.add() or .addCached() as described below, or provide a custom Formatter module via .use().
You may need to polyfill the Intl API:
Intl.NumberFormat (ES2020)
Intl.DateTimeFormat (ES2020)
π Check out this topic in the i18next crash course video.
Basic usage
The translation string has the following signature:
{
"key": "Some format {{value, formatname}}",
"keyWithOptions": "Some format {{value, formatname(option1Name: option1Value; option2Name: option2Value)}}"
}Use a "semicolon" delimited list of options.
Passing options to the formatting:
In the translation string using
{{value, formatname(options1: options1Value)}}Using the root level options when calling
t('key', { option1: option1Value })Using the per value options like:
t('key', { formatParams: { value: { option1: option1Value } })
Samples
Passing options to the formatting:
In the translation string using
{{value, formatname(options1: options1Value)}}Using the root level options when calling
t($ => $.key, { option1: option1Value })Using the per value options like:
t($ => $.key, { formatParams: { value: { option1: option1Value } })
Samples
Overriding the language to use
The language can be overridden by passing it in t.options
Adding custom format function
It's rather simple to add own function:
Make sure you add your custom format function AFTER the i18next.init() call.
There's also an addCached version for optimized performance:
Using multiple formatters
Built-in formats
Number
For options see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat
Currency
For options see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat
DateTime
For options see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
RelativeTime
For options see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat
List
For options see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat
Additional options
Prefix/Suffix for interpolation and other options can be overridden in init option:
sample
alwaysFormat
false
used to always call the format function for all interpolated values
formatSeparator
','
used to separate format from interpolation value
While there are a lot of options going with the defaults should get you covered.
Custom formatter
Do you want to create some sort of default formatter, that does not need a specific format to be passed via i18n resources? i18next gets you covered also with that...
Create a custom formatter plugin, and pass it to i18next:
Last updated