Localization in Elm with Plurals Support
Here’s the example of how you can localize your Elm application including plurals support.
The code is available in elm-samples
repository. It is based on the Elm i18n and Type Safety article by Amitai Burstein. Their solution provides the localization functionality with type safety.
The difference of my code is that I’ve added support for plurals.
Live demo:
Plurals Support
The logic for a pluralization is implemented in the PluralRules.elm
file.
The PluralRules
module exports functions that can be used for pluralized translation for a particular language.
As an example, there are functions for english
, french
, russian
, and german
languages.
Plural rules for a language can be found at the Unicode site. Different languages vary in how they support plurals, thus the amount of translations for a particular language will vary. This means that every translation function will take different amount of parameters.
For example, english
function takes two translations (one and other), and a number of items to provide the right plural form:
The russian
function requires four translations (one, few, many, and other):
How to Add Pluralization for New Language
Let’s add a support for a German language. Here’s the rules table from the Unicode site:
German language requires two translations for cardinal numbers: one, and other. The Rules
column contains the rules for pluralization, where:
i
is the integer digits of n.v
is the number of visible fraction digits in n, with trailing zeros.
The implementation for this logic in Elm:
Support for other languages can be added in a similar manner:
- Find the plural rules for a language in the Unicode table.
- Implement the rules in Elm as a separate function.
- Use the function in your code.