Managing multi-language content can be essential for providing a localized user experience. This article outlines two primary methods to handle multi-language data effectively. Both methods use ESL to filter and display content based on language and category.
Solution 1: Using foreach
The foreach loop is a way to iterate over a list of data items. It allows you to check each item against specific criteria and output the matching result. Here is an example of how to use foreach for multi-language handling:
Code Example
{% set mydata = [
{ "locale": "de-De", "category": 3, "job": "Arzthelferin" },
{ "locale": "en-US", "category": 4, "job": "Teacher" }
] %}
{% foreach item in mydata %}
{% if contact.locale == item.locale and contact.category == item.category %}
{{ item.job }}
{% endif %}
{% endforeach %} Limitations: The foreach loop can handle a maximum of 100 items. If your use case requires handling more items, consider using the second solution with the find.
Solution 2: Using find
The find function is an efficient way to retrieve the first matching item from a list based on specified criteria. It stops iterating as soon as it finds a match, making it more efficient for large datasets.
Advantages
- No Known Item Limit: Unlike foreach, there is no known upper limit to the number of items that find can handle.
- Efficient: It iterates only until it finds a matching item, reducing unnecessary iterations.
- Null Handling: If no matching item is found, find returns null. Combining this with filters like required can help manage errors effectively.
Code Example
{% set mydata = [
{ "locale": "de-De", "category": 3, "job": "Arzthelferin" },
{ "locale": "en-US", "category": 4, "job": "Teacher" }
] %}
FULL ROW AS RESULT: {{ mydata | find(item => item.locale == contact.locale and item.category == contact.category) | json_encode() }}
ONLY JOB AS RESULT: {{ mydata | find(item => item.locale == contact.locale and item.category == contact.category)["job"] }}
Explanation
- FULL ROW AS RESULT: This outputs the entire matching row as a JSON-encoded string.
- ONLY JOB AS RESULT: This outputs only the job field from the matching row.
Error Handling
To handle cases where no matching item is found, you can use the required filter. For instance:
{{ mydata | find(item => item.locale == event.locale and item.category == event.category)["job"] | required }}
This will trigger an error if no matching item is found, allowing you to handle such cases appropriately.
Conclusion
Both foreach and find are powerful tools for managing multi-language data in ESL. Choose foreach for simpler use cases with limited data and opt for find when dealing with larger datasets or requiring more efficient lookups.
By effectively utilizing these methods, you can provide a seamless and localized experience for your users across multiple languages.