Passing a custom variable to i18n

I Was going through the link below. Is it possible to pass a custom variable to it? Like {{ sub now.Year 2005 }} in the i18n file?

Yes, you can pass any variable to the message.

// i18n/en.toml
[results]
one = "Found 1 result in {{ .Time }}"
other = "Found {{ .Count }} results in {{ .Time }}"

[echo]
other = "echo {{ . }}"
{{- warnf "%v" (i18n "results" (dict "Count" 1 "Time" "10ms")) }}
{{- warnf "%v" (i18n "results" (dict "Count" 20 "Time" "0.2s")) }}
{{- warnf "%v" (i18n "echo" "Hi there!") }}
WARN 2023/04/20 21:41:22 Found 1 result in 10ms
WARN 2023/04/20 21:41:22 Found 20 results in 0.2s
WARN 2023/04/20 21:41:22 echo Hi there!

Explanation:

  • If I remember correctly, the Count is used to determine the singular (one) and plural (other).
  • You can access the data via context (AKA the dot .).
  • The Count isn’t required, you can pass data in any type, such as a string.
2 Likes

Correct.

1 Like

When dealing with pluralization, it’s important to remember that “one” does not mean 1. It is a cardinal category in the CLDR Pluralization Rules.

In some languages (e.g., English), the only number in the “one” category is 1. In other languages (e.g., Ukrainian) there are many numbers in the “one” category.

So it would be better to do:

one = "Found {{ .Count }} result in {{ .Time }}"
1 Like

I decided to split the i18n sentence into two and insert the year between the two statements. The implementation I wanted is complex and out of my ability.

{{ T "desc" }} {{ sub now.Year 2005 }} {{ T "desc-end" }}

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.