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:
javascriptimport 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.