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:

πŸŽ“ 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:

  1. In the translation string using {{value, formatname(options1: options1Value)}}

  2. Using the root level options when calling t('key', { option1: option1Value })

  3. 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:

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

option
default
description

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

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