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

How to translate dynamically properties of an array of objects with i18n?

1个答案

1

When addressing the need to implement i18n (internationalization) for dynamically translating property values of object arrays, the common approach is to combine frontend internationalization libraries (such as react-intl, i18next, etc.) with backend multilingual support. Here, we will provide a concrete example to illustrate the entire process in detail.

Assumed Scenario

Assume we have an e-commerce platform where the backend returns a product list. Each product object contains multiple properties, some of which require displaying different languages based on the user's language preference. For example, each object in the array might look like this:

json
[ { "id": 1, "name": "Laptop", "description": "High performance laptop", "price": "1000 USD" }, { "id": 2, "name": "Mouse", "description": "Wireless mouse", "price": "20 USD" } ]

Solution Steps

Step 1: Design Backend Data Structure

The backend should provide a data structure that supports multilingual content. One approach is to store multiple versions for each translatable field, for example:

json
[ { "id": 1, "name": { "en": "Laptop", "zh": "笔记本电脑" }, "description": { "en": "High performance laptop", "zh": "高性能笔记本电脑" }, "price": "1000 USD" }, { "id": 2, "name": { "en": "Mouse", "zh": "鼠标" }, "description": { "en": "Wireless mouse", "zh": "无线鼠标" }, "price": "20 USD" } ]

Step 2: Frontend Internationalization Processing

On the frontend, assuming the use of React and react-intl for internationalization:

  1. Configure Internationalization Library: First, set up the internationalization library, including required language packs and Provider components.

  2. Data Rendering: When rendering components, dynamically select property values based on the user's language settings.

jsx
import { useIntl } from 'react-intl'; function ProductList({ products }) { const intl = useIntl(); const currentLocale = intl.locale; // Retrieve current language setting return ( <div> {products.map(product => ( <div key={product.id}> <h2>{product.name[currentLocale]}</h2> <p>{product.description[currentLocale]}</p> <p>{product.price}</p> </div> ))} </div> ); }

Step 3: Testing and Validation

After implementation, conduct testing in multilingual environments to ensure all languages display correctly and there are no missing or incorrect translations.

Conclusion

By following these steps, we can achieve a flexible multilingual product list display, where the backend provides multilingual data and the frontend dynamically renders the appropriate language based on user settings. This method offers ease of maintenance and rapid adaptation to new language requirements, though careful attention must be paid to data structure design and frontend performance optimization.

2024年8月8日 16:42 回复

你的答案