Global access and scope
install
Create the instance once, then call t!("key") anywhere: handlers, Display of errors, Tauri commands, CLIs.
The Tauri plugin installs it for you.
I18n::builder().dir("locales").locale("ru").fallback("en").install()?; // once per process
// or: i18n_next::install(i18n.clone())?;
A second install returns Error::AlreadyInstalled; change the installed instance instead (set_locale, reload,
add_messages). global() returns it as an Option. Free functions act on the same instance:
i18n_next::t("key") (a Text), set_locale("de"), locale(), page("settings").
Macros
use i18n_next::{t, tc, key};
t!("welcome", name = user.name.clone());
t!("cart.summary", name = "Ann", count = n); // count picks the plural form
t!("pair", ["Ann", "Bob"]); // {0} {1}
t!("title", @page = "settings");
t!("title", @locale = "de", @or = "Title");
t!("terms", @html);
tc!("apples", 5); // t!("apples", count = 5)
t!(i18n => "nav.home"); // an explicit instance or view
Every macro returns a lazy Text. Options start with @, so a {page} parameter stays a
parameter. @number = n, @date = t and @relative = t fill {number}, {date} and {relativeDate}. tn!,
td! and tdr! format right away and return a String (Formats).
key!
const QUIT: Key = key!("menu.quit"); // a const
println!("{QUIT}"); // resolved now, through scope and the global instance
QUIT.args().arg("app", "Demo"); // a Text
#[derive(thiserror::Error, Debug)]
enum AppError {
#[error("{}", key!("errors.not_found"))] NotFound,
#[error("{}", t!("errors.io", path = .0.display().to_string()))] Io(std::path::PathBuf),
}
scope
Set the locale, page or instance for a request or task without passing them down (run(locale, fn) of
@i18n-micro/node):
i18n_next::scope().locale("de").page("checkout").run(|| render());
// any async runtime
async fn locale_mw(req: Request, next: Next) -> Response {
let accept = req.headers().get("accept-language").and_then(|v| v.to_str().ok()).unwrap_or("");
let lang = i18n_next::negotiate(accept, ["en", "de", "ru"]).unwrap_or_else(|| "en".into());
i18n_next::scope().locale(lang).wrap(next.run(req)).await
}
- A text without its own instance, locale or page takes each from the nearest scope that sets it; an inner scope overrides one part and inherits the rest.
.locale/.pageon aText(or@locale/@page, or aView) beat the scope.- Without any instance the key is shown, with a warning on stderr in debug builds.
wrapworks with any runtime: tokio, smol,wasm-bindgen-futures, Tauri's.
negotiate(header, available) takes an Accept-Language header or a comma-separated list
(navigator.languages) and returns the best code as available spells it: by q, then de-AT → de-at → de →
any de-*. Case and _ do not matter; q=0 is never chosen.
In tests
Don't share the global instance between tests. Give each test its own, with a fixed zone and clock:
let i18n = I18n::builder()
.messages("en", None, r#"{"a": "A"}"#)
.time_zone("UTC")
.clock(|| 1_704_428_640_000)
.build()?;
i18n_next::scope().instance(i18n).run(|| {
assert_eq!(t!("a").to_string(), "A");
});
scope().instance affects only this thread or task, so tests run in parallel. To test relative dates, let the
clock read a shared AtomicI64 and move it. assert!(i18n.check().is_clean()) catches missing keys
(Checks).