Translating
Lookups
use i18n_next::Args;
i18n.t("nav.home"); // &str: the text, or the key on a miss
i18n.t_with("greeting", &Args::new().str("name", "Ann")); // String, parameters filled in
i18n.t_with("cart", &Args::new().int("n", 2).or("{n} items")); // with a default for a miss
i18n.get("nav.nope"); // Option<&str>: None on a miss
i18n.has("nav.home"); // bool: the active locale only
| Call | Returns | On a miss |
|---|---|---|
t(key) | &str, the stored text, {name} left as written | the key; calls missing |
t_with(key, &args) | String with parameters filled in | the default (Args::or, interpolated), else the key; calls missing |
get(key) | Option<&str>, the stored text | None; never calls missing |
has(key) | bool | checks the active locale's page and root, never the fallback (as JS has()) |
A subtree (t("nav")) returns the key without calling missing; get returns None for it. t and get
allocate nothing, and the &str stays valid after set_locale or reload: texts are stored once for the life of
the process (equal texts share one copy), so a reload keeps memory only for texts it has not seen before.
Parameters
{ "welcome": "Hello, {name}!", "pair": "{0} and {1}" }
use i18n_next::{Arg, Args, t};
i18n.t_with("welcome", &Args::new().str("name", "Ann"));
i18n.t_with("pair", &Args::list(["Ann", "Bob"]));
t!("welcome", name = user.name.clone());
t!("pair", ["Ann", "Bob"]);
t!("errors.io", path = Arg::display(p.display())); // any Display value
t!("kw", r#type = "a"); // raw identifier: fills {type}
t!("hello", who = i18n.text("user.guest")); // a translation inside a translation
t!("due", when = Arg::date_as(d, "short")); // a formatted date, see Formats
- A placeholder is
{name}without spaces or braces;{0},{1}take items of a list. - A placeholder without a value stays in the text as written, like in JS.
- Plain numbers are inserted as JS
String(value)prints them. OnlyArg::Number { .. },Arg::date,Arg::date_asandArg::relativeare localized (Formats). - A nested
Textis resolved each time the outer one is shown, in the outer text's locale and page unless it sets its own.
Values convert into Arg from strings, char, integers, floats, bool, Text and Key; any other Display
value goes through Arg::display.
Plurals
Forms are separated by |:
{
"car": "car | cars",
"apples": "нет яблок | {count} яблоко | {count} яблока | {count} яблок",
"cart": "=0 Your cart is empty | {count} item | {count} items"
}
i18n.tc("car", 2); // "cars"
i18n.tc("apples", 21); // "21 яблоко" (ru)
i18n.tc("cart", 0); // "Your cart is empty"
i18n.tc_with("greet", 3, &Args::new().str("name", "Ann"));
t!("apples", count = 5); tc!("apples", 5); // the same as macros
The form is picked as pluralForm in @i18n-micro/core does it:
- by default, by index: form number
count, the last form past the end (car | cars: 0 →car); - a zero form without
{, then one form per CLDR category of the locale (Russian:one,few,many): by category. Used for locales with three or more such categories; - a first form starting with
=0: that form for 0, the rest by category; - a negative, fractional or
NaNcount takes the last form.
{count} is filled with the count and wins over an argument named count. A value without | is its one form.
On a miss tc returns the default (Args::or) or the key and calls missing. t("car") returns the whole
string with its pipes.
Rules go by the locale's iso (from i18n.json or .iso("ua", "uk-UA")), else its code. A tag without plural
rules uses the index rule.
Fallback and missing keys
let i18n = I18n::builder()
.locale("de-at")
.fallback("en") // global fallback: the last layer of every chain
.fallback_for("de-at", "de") // de-at → de → en
.missing(|locale, key, page| eprintln!("missing {locale}/{page}/{key}"))
.build()?;
- Each locale has a chain, as in Nuxt:
de-at → de → en.fallbackLocaleper locale ini18n.jsonadds the same steps. A cycle stops at the first repeat. - A locale needs no file of its own:
.fallback_for("de-ch", "de")is enough toset_locale("de-ch"). - On a miss
missing(locale, key, page)is called (the root page is"index") and the key or the default is returned.getnever calls it. set_localerefuses a locale nothing defines (Error::UnknownLocale) or onei18n.jsondisables (Error::DisabledLocale).
In a Tauri dev build the plugin also collects misses from the frontend: see Tauri.
Pages
The catalog is split into the root and pages (Layout). The first match wins:
- the page in the active locale;
- the root in the active locale;
- the page in the fallback locale;
- the root in the fallback locale;
- and so on down the chain.
let settings = i18n.page("settings"); // a View: cheap, Clone + Send + Sync
settings.t("title");
settings.t_with("hint", &Args::new().int("n", 3));
i18n.with_locale("de").t("title"); // another locale, without switching
i18n.with_locale("de").page("settings").t("title");
i18n.pages(); // known pages: ["settings", "user-profile"]
i18n.add_messages("en", Some("settings"), r#"{"saved": "Saved"}"#)?;
A View has the same lookups as I18n. page("") and page("index") are the root; a page without a file reads
the root. A page is just a name: it can match a frontend route (settings) or be a Rust-only area (tray,
notifications, cli). The frontend never loads a page it does not ask for.
| Builder | JS equivalent | Effect |
|---|---|---|
.pages(false) | disablePageLocales | page files merge into the root |
.page_alias("about-us", "about") | routesLocaleLinks | a page reads another page's file |
.evict_pages(n) | keep at most n loaded pages, see Loading |
Text
Text is a lazy translation, the Rust counterpart of <i18n-t>. Nothing is looked up until it is shown, and it is
resolved again each time: a Text kept in UI state shows the new language after set_locale.
let total = i18n.text("cart.total") // or t!("cart.total", …), View::text, Key::args
.arg("name", user.name.clone())
.count(items.len()) // plural form and {count}
.or("Total") // shown on a miss
.page("checkout")
.locale("de");
println!("{total}"); // Display
total.to_string();
total.resolve(); // Option<String>: None on a miss without .or, or when hidden
total.write_to(&mut buf)?; // into your buffer
assert_eq!(total, "Gesamt: 3"); // compares with &str
<i18n-t> prop | Text |
|---|---|
keypath | i18n.text(key), t!(key) |
params | .arg(name, value), .args([a, b]) for {0}, {1} |
plural | .count(n) |
defaultValue | .or(..) |
hideIfEmpty | .hide_if_empty() |
customPluralRule | .plural_rule(|ctx| ..) |
html | .html() |
number, date, relativeDate | .number / .date / .relative (.number_as / .date_as for a named format) |
- Locale and page: set on the
Text, else the nearest scope, else the active locale and the root. - A miss calls
missingand shows the.ordefault, else the key. Both are interpolated. .html()escapes text arguments (&<>"'); the translation itself is trusted markup..hide_if_empty(): blank text resolves toNoneand shows the.ordefault, or nothing..plural_rule(|ctx| ..)replaces the plural rule when a count is set;ctx.key,ctx.count,ctx.locale,ctx.get(key).
Text is 'static + Send + Sync + Clone. With the serde feature it serializes as the shown string, so a Tauri
command or an HTTP handler can return it.
Rich text
For messages with slots, such as "I accept the {link} and the {policy}.":
let pieces: Vec<Widget> = i18n.text("terms").fold(
|text| Widget::label(text),
&[("link", &|| Widget::link("terms", URL)), ("policy", &|| Widget::link("policy", URL2))],
);
for part in i18n.text("terms").arg("who", "Ann").parts() {
match part {
Part::Text(s) => { /* plain text, arguments filled in */ }
Part::Slot(name) => { /* a placeholder no argument fills: your widget */ }
}
}
fold turns each slot into the slot's node and each run of text into a node from your closure. A slot wins over an
argument of the same name. parts gives the same pieces as a list. Both work with any UI framework.
let nodes: Vec<AnyView> = t!("terms").fold(
|text| text.to_owned().into_any(),
&[
("link", &|| view! { <a href="/terms">{t!("terms_link").to_string()}</a> }.into_any()),
("policy", &|| view! { <a href="/privacy">{t!("policy_link").to_string()}</a> }.into_any()),
],
);
view! { <p>{nodes}</p> } // build inside the reactive closure so it re-folds after a locale switch
ui.horizontal_wrapped(|ui| {
for part in t!("terms").parts() {
match part {
Part::Text(s) => { ui.label(s.as_ref()); }
Part::Slot(name) if name == "link" => { ui.hyperlink_to(t!("terms_link").to_string(), TERMS_URL); }
Part::Slot(name) if name == "policy" => { ui.hyperlink_to(t!("policy_link").to_string(), PRIVACY_URL); }
Part::Slot(_) => {}
}
}
});
let line = Line::from(t!("terms").fold(
|text| Span::raw(text.to_owned()),
&[("link", &|| "terms".underlined()), ("policy", &|| "privacy policy".underlined())],
));
In templates (askama and others) Text prints as is. For markup build it with .html() and mark it safe; a nested
html text argument is inserted as is:
i18n.text("terms").html().arg("link", i18n.text("terms_link_html").html()).