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

How can I pass parameters with i18next?

1个答案

1

When working with i18next for internationalization, you frequently need to insert dynamic parameters into translation strings. i18next provides a flexible approach to handle this, allowing you to embed variables within translation text and dynamically replace them at runtime.

Basic Usage

First, define translation strings with variables in your resource files. In i18next, parameters are enclosed using {{}}. For example, consider the following key-value pair:

json
{ "greeting": "Hello, {{name}}! Welcome to {{place}}." }

Here, {{name}} and {{place}} represent the dynamic parameters you will pass.

Passing Parameters in Code

Next, when invoking the translation function (typically t) in your code, pass the variable values as an object as the second argument:

javascript
i18next.t('greeting', { name: 'Alice', place: 'Wonderland' });

This code will output: "Hello, Alice! Welcome to Wonderland."

Application Example

Suppose you are developing a multi-language e-commerce site that needs to display a welcome message dynamically based on the user's name and the page they are visiting. You can implement this as follows:

  1. Define parameterized strings in your language resource files:

    json
    { "welcomeMessage": "Hi, {{name}}! Check out our latest offers on {{product}}." }
  2. In your application, dynamically generate the message using user-specific data:

    javascript
    const userName = 'John'; const productName = 'smartphones'; const message = i18next.t('welcomeMessage', { name: userName, product: productName }); console.log(message); // Output: Hi, John! Check out our latest offers on smartphones.

This approach not only enables your application to support multiple languages but also allows for flexible presentation of personalized information to users.

Summary

By leveraging i18next's parameter passing capabilities, you can efficiently handle complex, dynamic multilingual text. This is especially valuable for internationalizing user interfaces, significantly improving user experience. Whether it involves simple name substitutions or dynamically adjusting messages based on user behavior, i18next delivers robust support.

2024年6月29日 12:07 回复

你的答案