You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用i18next获取指定key对应所有语言的翻译内容?

实现方案

你可以直接基于i18n已有的t()方法封装通用工具函数即可,核心逻辑是遍历所有支持的语言,调用t()时显式指定lng参数切换语言,最终返回多语言键值对。

基础实现(无插值参数)

首先确保你的i18next实例已经预加载了所有支持语言的翻译资源,不要使用按需加载的模式,否则无法获取未加载语言的翻译内容。

// 导入你项目中已经初始化完成的i18n实例
import i18n from './i18n/config'

// 封装你需要的多语言获取方法
const getTranslationsForAllLangs = (key) => {
  // 可直接从i18n配置中读取支持的语言列表,过滤掉i18n默认的调试语言cimode
  const supportedLangs = i18n.options.supportedLngs.filter(lang => lang !== 'cimode')
  const translationMap = {}

  supportedLangs.forEach(lang => {
    // 显式指定lng参数获取对应语言的翻译
    translationMap[lang] = i18n.t(key, { lng: lang })
  })

  return translationMap
}

使用方式和你预期的完全一致:

// 路由返回逻辑
res.json({
  errors: [
    { messages: getTranslationsForAllLangs('password_short') }
  ]
})

进阶实现(支持插值参数)

如果你的翻译内容包含动态插值变量,比如密码长度限制提示需要传入最小长度参数,可以扩展函数支持传入配置项:

const getTranslationsForAllLangs = (key, options = {}) => {
  const supportedLangs = i18n.options.supportedLngs.filter(lang => lang !== 'cimode')
  const translationMap = {}

  supportedLangs.forEach(lang => {
    translationMap[lang] = i18n.t(key, { ...options, lng: lang })
  })

  return translationMap
}

// 使用示例:翻译key为password_min_length,插值参数length为8
getTranslationsForAllLangs('password_min_length', { length: 8 })

全局扩展(可选)

你也可以直接把方法挂载到i18n实例上,全局无需重复导入:

// i18n初始化完成后挂载扩展方法
i18n.init({
  // 原有配置:supportedLngs、resources、fallbackLng等
}).then(() => {
  i18n.getAllT = getTranslationsForAllLangs
})

// 任意位置直接调用
i18n.getAllT('password_short')

注意事项

  • 如果你的项目使用了后端插件异步加载语言包,需要提前调用i18n.loadLanguages(['de', 'en'])预加载所有支持的语言,否则未加载的语言会返回key本身而非翻译内容。
  • 如果支持的语言数量较多不想全部预加载,可以在函数内补充语言加载逻辑,等所有语言资源加载完成后再返回结果即可。

内容的提问来源于stack exchange,提问作者Pascal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 03:39:00