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

在生成gettext .po文件时如何在i18next.t()中使用数字变量

Handling Dynamic Variables in i18next + Gettext Setup

Great question—this is a super common need when working with dynamic content, and luckily i18next’s built-in interpolation plays perfectly with your existing gettext-based workflow. Here’s how to implement it step by step:

1. Update Your Translation Template & Key

Even with your "English string as key" approach, i18next supports interpolation placeholders for dynamic values. Modify your translation.json entry to include a placeholder for the age:

{
  "Must be {{minAge}} years or older!": "Must be {{minAge}} years or older!"
}

The {{minAge}} tag is the placeholder that will get replaced with your dynamic value at runtime.

2. Pass Dynamic Values in Your React Code

When calling i18next.t(), add a second argument to inject your variable—this works for both hardcoded values and data fetched from your backend:

For fixed values (like your original 12 example):

i18next.t('Must be {{minAge}} years or older!', { minAge: 12 });

For backend-provided dynamic values:

// Fetch the age limit from your backend
const fetchMinAge = async () => {
  const response = await fetch('/api/age-restriction');
  const data = await response.json();
  return data.minAge;
};

// Use the dynamic value in your translation
const minAge = await fetchMinAge();
const errorMessage = i18next.t('Must be {{minAge}} years or older!', { minAge });

3. Verify the .po File Conversion

When you run i18next-conv to convert your updated translation.json to a .po file, the placeholder will be preserved automatically. Your generated .po file will look like this:

msgid "Must be {{minAge}} years or older!"
msgstr ""

Translators can then translate the surrounding text while leaving the {{minAge}} placeholder intact. For example, a French translation would be:

msgid "Must be {{minAge}} years or older!"
msgstr "Vous devez avoir au moins {{minAge}} ans !"

Optional: Refactor to Concise Keys (If You Prefer)

If you want cleaner, more reusable keys instead of full sentences, you can refactor to a shorter key while keeping the interpolation. For example:

Update translation.json:

{
  "error.age.minimum": "Must be {{minAge}} years or older!"
}

Then call it in code:

i18next.t('error.age.minimum', { minAge: minAgeFromBackend });

This is great if you reuse the same error pattern across multiple components—no need to repeat the full sentence as a key.

This approach keeps your existing gettext workflow intact, maintains full flexibility for dynamic values, and works seamlessly with i18next and i18next-conv.

内容的提问来源于stack exchange,提问作者Barry Michael Doyle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 08:37:29