Pluralization

Iris i18n supports plural variables. To define a per-locale variable you must define a new section of Vars key.

The acceptable keys for variables are:

  • one
  • "=x" where x is a number
  • "<x"
  • other
  • format

Example:

  1. Vars:
  2. - Minutes:
  3. one: "minute"
  4. other: "minutes"
  5. - Houses:
  6. one: "house"
  7. other: "houses"

Then, each message can use this variable, here’s how:

  1. # Using variables in raw string
  2. YouLate: "You are %[1]d ${Minutes} late."
  3. # [x] is the argument position,
  4. # variables always have priority other fmt-style arguments,
  5. # that's why we see [1] for houses and [2] for the string argument.
  6. HouseCount: "%[2]s has %[1]d ${Houses}."
  1. ctx.Tr("YouLate", 1)
  2. // Outputs: You are 1 minute late.
  3. ctx.Tr("YouLate", 10)
  4. // Outputs: You are 10 minutes late.
  5. ctx.Tr("HouseCount", 2, "John")
  6. // Outputs: John has 2 houses.

You can select what message will be shown based on a given plural count.

Except variables, each message can also have its plural form too!

Acceptable keys:

  • zero
  • one
  • two
  • "=x"
  • "<x"
  • ">x"
  • other

Let’s create a simple plural-featured message, it can use the Minutes variable we created above too.

  1. FreeDay:
  2. "=3": "You have three days and %[2]d ${Minutes} off." # "FreeDay" 3, 15
  3. one: "You have a day off." # "FreeDay", 1
  4. other: "You have %[1]d free days." # "FreeDay", 5
  1. ctx.Tr("FreeDay", 3, 15)
  2. // Outputs: You have three days and 15 minutes off.
  3. ctx.Tr("FreeDay", 1)
  4. // Outputs: You have a day off.
  5. ctx.Tr("FreeDay", 5)
  6. // Outputs: You have 5 free days.

Let’s continue with a bit more advanced example, using template text + functions + plural + variables.

  1. Vars:
  2. - Houses:
  3. one: "house"
  4. other: "houses"
  5. - Gender:
  6. "=1": "She"
  7. "=2": "He"
  8. VarTemplatePlural:
  9. one: "${Gender} is awesome!"
  10. other: "other (${Gender}) has %[3]d ${Houses}."
  11. "=5": "{{call .InlineJoin .Names}} are awesome."
  1. const (
  2. female = iota + 1
  3. male
  4. )
  5. ctx.Tr("VarTemplatePlural", iris.Map{
  6. "PluralCount": 5,
  7. "Names": []string{"John", "Peter"},
  8. "InlineJoin": func(arr []string) string {
  9. return strings.Join(arr, ", ")
  10. },
  11. })
  12. // Outputs: John, Peter are awesome
  13. ctx.Tr("VarTemplatePlural", 1, female)
  14. // Outputs: She is awesome!
  15. ctx.Tr("VarTemplatePlural", 2, female, 5)
  16. // Outputs: other (She) has 5 houses.