Ajouve
Ajouve

Reputation: 10049

i18next interpolation defaultVariables from backend

I have the following i18n setup on my react

import i18n from 'i18next'
import LanguageDetector from 'i18next-browser-languagedetector'
import {initReactI18next} from 'react-i18next'
import Backend from 'i18next-http-backend';

i18n
    .use(initReactI18next)
    .use(LanguageDetector)
    .use(Backend)
    .init({
        backend: {
            loadPath: `test.com`,
        },
        react: {
            useSuspense: false
        },
        whitelist: ['en', 'fr', 'es'],
        fallbackLng: ['en'],
        detection: {
            order: ['cookie', 'navigator'],
            lookupCookie: 'i18nextLng',
            caches: ['cookie'],
            cookieOptions: { path: '/', sameSite: 'strict' },
            checkWhitelist: true
        }
    })

export default i18n

I have a unique product with some information as price I would like to use as defaultVariables

Reading the doc I can change the inti config adding

{
    interpolation: {
        defaultVariables: {price: 100}
    }
}

and then {{price}} should be available on all my translations

This part is working great.

But I am getting the product from a server call and I can not find any way to update the defaultVariables once i18n has been initialized

Upvotes: 0

Views: 1181

Answers (1)

adrai
adrai

Reputation: 3168

Officially, the only way to have defaultVariables injected is via init function. This means you have to load those values before calling init(), and then pass them via init options.

But....

you can try to do this:

i18next.services.interpolator.options.interpolation.defaultVariables = { price: 100 }

This may work, but this is for sure unsupported and not recommended.

btw: the whitelist option was replaced with supportedLngs: https://www.i18next.com/misc/migration-guide#removed-deprecated

Upvotes: 2

Related Questions