乐闻世界logo
搜索文章和话题

How to use interpolation, pluralization, and context in i18next?

2月18日 22:06

Basic Translation

Use the t() function for translation:

javascript
// simple translation t('welcome'); // "Welcome" // nested keys t('header.title'); // "Dashboard"

Interpolation

Variable Interpolation

Use {{variable}} syntax in translation text:

javascript
// translation resources { "greeting": "Hello {{name}}", "userCount": "Total users: {{count}}" } // usage t('greeting', { name: 'John' }); // "Hello John" t('userCount', { count: 100 }); // "Total users: 100"

Array Interpolation

javascript
{ "list": "Items: {{items}}" } t('list', { items: ['apple', 'banana'].join(', ') });

Pluralization

i18next has built-in support for plurals:

javascript
// translation resources { "item": "one item", "item_plural": "{{count}} items" } // usage t('item', { count: 1 }); // "one item" t('item', { count: 5 }); // "5 items"

Custom Plural Rules

javascript
i18next.init({ lng: 'ru', resources: { ru: { translation: { "item_one": "один предмет", "item_few": "{{count}} предмета", "item_many": "{{count}} предметов", "item_other": "{{count}} предмет" } } } });

Context Handling

Display different translations based on context:

javascript
// translation resources { "friend": "A friend", "friend_male": "A boyfriend", "friend_female": "A girlfriend" } // usage t('friend', { context: 'male' }); // "A boyfriend" t('friend', { context: 'female' }); // "A girlfriend"

Namespaces

Using Namespaces

javascript
i18next.init({ ns: ['common', 'errors'], defaultNS: 'common', resources: { en: { common: { "save": "Save" }, errors: { "notFound": "Not found" } } } }); // usage t('save'); // use default namespace t('errors:notFound'); // specify namespace

Dynamic Namespace Loading

javascript
i18next.loadNamespaces(['admin', 'settings'], () => { // namespaces loaded });

Formatting

Custom Formatting Functions

javascript
i18next.init({ interpolation: { format: function(value, format, lng) { if (format === 'uppercase') { return value.toUpperCase(); } if (format === 'currency') { return new Intl.NumberFormat(lng, { style: 'currency', currency: 'USD' }).format(value); } return value; } } }); // usage t('price', { price: 100, formatParams: { price: { format: 'currency' } } });

Nested Translation

javascript
// translation resources { "user": { "profile": { "name": "Name: {{name}}" } } } // usage t('user.profile.name', { name: 'John' });

Missing Translation Handling

javascript
i18next.init({ saveMissing: true, missingKeyHandler: (lng, ns, key) => { console.log(`Missing translation: ${lng}.${ns}.${key}`); } });

Performance Optimization

javascript
// batch translation const keys = ['welcome', 'goodbye', 'save']; const translations = keys.map(key => t(key)); // cache translation results const cachedTranslations = new Map(); function getCachedTranslation(key, options) { const cacheKey = `${key}_${JSON.stringify(options)}`; if (!cachedTranslations.has(cacheKey)) { cachedTranslations.set(cacheKey, t(key, options)); } return cachedTranslations.get(cacheKey); }
标签:i18next