Formatting
Starting with i18next>=21.3.0 you can use the built-in formatting functions based on the Intl API.
You may need to polyfill the Intl API:
Intl.NumberFormat (ES2020)
Intl.DateTimeFormat (ES2020)
Basic usage
The translation string has the following signature:
{
"key": "Some format {{value, formatname}}",
"keyWithOptions": "Some format {{value, formatname(option1Name: option1Value; option2Name: option2Value)}}"
}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
Legacy format function i18next<21.3.0
You can add formatting using moment.js and numeral.js or the intl api.
As a sample using momentjs to format dates.
keys
Init i18next with a format function:
sample
Keep the language on moment in sync with i18next by listening to the change language event:
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
format
noop function
Passing this function is considered LEGACY in i18next>=21.3.0
format function function format(value, format, lng, edit) {}
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
Create a custom formatter plugin, and pass it to i18next:
Last updated