基本翻译
使用 t() 函数进行翻译:
javascript// 简单翻译 t('welcome'); // "Welcome" // 嵌套键 t('header.title'); // "Dashboard"
插值功能
变量插值
在翻译文本中使用 {{variable}} 语法:
javascript// 翻译资源 { "greeting": "Hello {{name}}", "userCount": "Total users: {{count}}" } // 使用 t('greeting', { name: 'John' }); // "Hello John" t('userCount', { count: 100 }); // "Total users: 100"
数组插值
javascript{ "list": "Items: {{items}}" } t('list', { items: ['apple', 'banana'].join(', ') });
复数处理
i18next 内置对复数的支持:
javascript// 翻译资源 { "item": "one item", "item_plural": "{{count}} items" } // 使用 t('item', { count: 1 }); // "one item" t('item', { count: 5 }); // "5 items"
自定义复数规则
javascripti18next.init({ lng: 'ru', resources: { ru: { translation: { "item_one": "один предмет", "item_few": "{{count}} предмета", "item_many": "{{count}} предметов", "item_other": "{{count}} предмет" } } } });
上下文处理
根据上下文显示不同的翻译:
javascript// 翻译资源 { "friend": "A friend", "friend_male": "A boyfriend", "friend_female": "A girlfriend" } // 使用 t('friend', { context: 'male' }); // "A boyfriend" t('friend', { context: 'female' }); // "A girlfriend"
命名空间
使用命名空间
javascripti18next.init({ ns: ['common', 'errors'], defaultNS: 'common', resources: { en: { common: { "save": "Save" }, errors: { "notFound": "Not found" } } } }); // 使用 t('save'); // 使用默认命名空间 t('errors:notFound'); // 指定命名空间
动态加载命名空间
javascripti18next.loadNamespaces(['admin', 'settings'], () => { // 命名空间加载完成 });
格式化
自定义格式化函数
javascripti18next.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; } } }); // 使用 t('price', { price: 100, formatParams: { price: { format: 'currency' } } });
嵌套翻译
javascript// 翻译资源 { "user": { "profile": { "name": "Name: {{name}}" } } } // 使用 t('user.profile.name', { name: 'John' });
缺失翻译处理
javascripti18next.init({ saveMissing: true, missingKeyHandler: (lng, ns, key) => { console.log(`Missing translation: ${lng}.${ns}.${key}`); } });
性能优化
javascript// 批量翻译 const keys = ['welcome', 'goodbye', 'save']; const translations = keys.map(key => t(key)); // 缓存翻译结果 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); }