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

How to replace variables in i18next

1个答案

1

Replacing variables in i18next is primarily achieved by using variable placeholders within translation strings and passing specific variable values during translation. This approach allows you to adapt to different language environments or dynamic content without modifying your code, as all text is centralized in translation files. Below are the specific steps and examples:

Step 1: Prepare Translation Files

First, define translation strings with variables in your resource files. For example, consider an English translation file en/translation.json containing:

json
{ "greeting": "Hello, {{name}}! You have {{count}} new messages." }

Here, {{name}} and {{count}} serve as placeholders for variables to be replaced.

Step 2: Use Translation in Code

Next, retrieve the translation string with variables in your application using i18next. Pass the corresponding variable values when calling the translation function:

javascript
import i18n from 'i18next'; i18n.init({ // Initialization configuration... }); // Assume user name and message count are dynamically retrieved const userName = "John"; const userMessages = 5; const greeting = i18n.t('greeting', { name: userName, count: userMessages }); console.log(greeting); // Output: Hello, John! You have 5 new messages.

Example Explanation

In this example, the first parameter of i18n.t is the translation key 'greeting', while the second parameter is an object containing all variables to replace. i18next automatically identifies placeholders like {{name}} and {{count}}, substituting them with the provided values.

Summary

Managing variable replacement with i18next enables your application to support multiple languages and dynamically display data. This method streamlines code maintenance by centralizing all text in translation files, making updates and modifications straightforward.

2024年8月8日 15:09 回复

你的答案