Skip to main content

Module i18n

Module i18n 

Source
Expand description

Translations (18.16.0, #33): message catalogs, one per language, and the language each request asks for.

use rust_web_server::i18n::Catalogs;

let catalogs = Catalogs::new("en")
    .add("en", r#"
        greeting = "Hello, {name}!"
        items.one = "{count} item"
        items.other = "{count} items"
    "#).unwrap()
    .add("uk", r#"
        greeting = "Привіт, {name}!"
        items.one = "{count} річ"
        items.few = "{count} речі"
        items.many = "{count} речей"
    "#).unwrap();

// In a handler: catalogs.for_request(&request) reads Accept-Language.
let t = catalogs.translator("uk-UA,uk;q=0.9,en;q=0.5");
assert_eq!("uk", t.locale());
assert_eq!("Привіт, Олена!", t.t_with("greeting", &[("name", "Олена")]));
assert_eq!("3 речі", t.plural("items", 3));
assert_eq!("5 речей", t.plural("items", 5));

Catalog files are a flat subset of TOML (key = "value", # comments, \n \t \" \\ \u{…} escapes), one per language: Catalogs::from_dir reads <dir>/<language>.toml. A key missing in the chosen language falls back to its base language (en-GB → en), then the default language, then the key itself.

Structs§

AcceptLanguage
A client’s language preferences, from Accept-Language: tags in the order to try them (highest q first, then header order), lower-cased. Ranges with q=0 are left out; * is kept as "*".
Catalog
One language’s messages.
Catalogs
Every language’s catalog and the default language.
Translator
Messages in one language.

Constants§

MAX_LANGUAGE_RANGES
At most this many Accept-Language entries are considered (the header is the client’s to make arbitrarily long).

Functions§

plural_category
The CLDR plural category of a whole count in language: "one", "few", "many" or "other". Covered: East Slavic and Polish (uk, ru, be, pl: one/few/many), Czech and Slovak (one/few), French and Brazilian Portuguese (0 and 1 are one), languages without plural forms (ja, zh, ko, vi, th, id, ms, tr… : other); every other language uses English’s one/other.