pub struct Translator { /* private fields */ }Expand description
Translation backend — keyed by (locale, key).
Implementations§
Source§impl Translator
impl Translator
Sourcepub fn with_fallback_chain(self, chain: &[&str]) -> Self
pub fn with_fallback_chain(self, chain: &[&str]) -> Self
Set an explicit fallback chain. When
translate(locale, key, ...) doesn’t find a key in locale
or its base language, the lookup walks chain in order
before falling through to the default locale.
// Spanish missing? try Portuguese, then English (default).
let t = Translator::new(Locale::new("en"))
.with_fallback_chain(&["pt"]);Duplicate entries and entries equal to default_locale are
silently dropped (the default-locale check is already at the
end of the chain).
Sourcepub fn fallback_chain(&self) -> &[Locale]
pub fn fallback_chain(&self) -> &[Locale]
Current explicit fallback chain (without the implicit default-locale terminus). Useful for diagnostics.
Sourcepub fn add_locale(
self,
locale: Locale,
catalog: HashMap<String, String>,
) -> Self
pub fn add_locale( self, locale: Locale, catalog: HashMap<String, String>, ) -> Self
Add a translation catalog for locale. Replaces any existing
catalog for the same locale.
Sourcepub fn insert_locale(&self, locale: Locale, catalog: HashMap<String, String>)
pub fn insert_locale(&self, locale: Locale, catalog: HashMap<String, String>)
Mutably add a catalog (use with let mut t = ...).
Sourcepub fn add_plural_locale(
self,
locale: Locale,
catalog: HashMap<String, HashMap<String, String>>,
) -> Self
pub fn add_plural_locale( self, locale: Locale, catalog: HashMap<String, HashMap<String, String>>, ) -> Self
Add a plural catalog for locale (#1102). Each key maps to a small
object of CLDR plural-category → template, e.g.
{"one": "Deleted {count} page.", "other": "Deleted {count} pages."}.
Replaces any existing plural catalog for the same locale.
Sourcepub fn insert_plural_locale(
&self,
locale: Locale,
catalog: HashMap<String, HashMap<String, String>>,
)
pub fn insert_plural_locale( &self, locale: Locale, catalog: HashMap<String, HashMap<String, String>>, )
Mutably add a plural catalog (use with let mut t = ...).
Sourcepub fn translate(
&self,
locale: &str,
key: &str,
params: &[(&str, &str)],
) -> String
pub fn translate( &self, locale: &str, key: &str, params: &[(&str, &str)], ) -> String
Look up key in locale’s catalog, walking the fallback
chain in order: exact locale → base language → explicit
fallback_chain (#425) → default locale → key itself.
params substitutes {name} placeholders in the result.
Sourcepub fn translate_plural(
&self,
locale: &str,
key: &str,
n: i64,
params: &[(&str, &str)],
) -> String
pub fn translate_plural( &self, locale: &str, key: &str, n: i64, params: &[(&str, &str)], ) -> String
Count-aware translation (#1102) — the ngettext shape. Picks the plural
form for n via locale’s CLDR rule (plural_category), then
substitutes params (pass the count itself, e.g.
&[("count", &n.to_string())], so the chosen form’s {count} fills in).
When no plural entry exists for key in any locale, this falls back to
the scalar Self::translate — i.e. a flat catalog entry if present,
else the source key itself — so untranslated / English strings still
render (with {count} interpolated) instead of a blank or raw id.
// en plural catalog: "Deleted {count} page(s)." =>
// {"one": "Deleted {count} page.", "other": "Deleted {count} pages."}
let n = 3;
t.translate_plural("en", "Deleted {count} page(s).", n, &[("count", &n.to_string())]);
// => "Deleted 3 pages."Sourcepub fn has_locale(&self, locale: &str) -> bool
pub fn has_locale(&self, locale: &str) -> bool
true when strings are registered for locale (or its base
language) in either the file/programmatic catalogs or the DB
override layer (#532) — so a locale supplied only via
Self::load_overrides is reported as available too.
Sourcepub fn locales(&self) -> Vec<String>
pub fn locales(&self) -> Vec<String>
All registered locale identifiers (for negotiate_language).
Sourcepub fn entries(&self) -> Vec<(String, String, String)>
pub fn entries(&self) -> Vec<(String, String, String)>
Every file-catalog entry as (locale, key, value) triples — used
to seed the editable DB layer from the on-disk defaults (#532).
Sourcepub fn load_overrides(
&self,
rows: impl IntoIterator<Item = (String, String, String)>,
)
pub fn load_overrides( &self, rows: impl IntoIterator<Item = (String, String, String)>, )
Replace the entire DB-override layer (#532) with rows
((locale, key, value) triples — typically every
rustango_translations row). Locale strings are normalized the
same way as catalog locales. See
crate::i18n::db::refresh_overrides_pool.
Sourcepub fn set_override(
&self,
locale: &str,
key: impl Into<String>,
value: impl Into<String>,
)
pub fn set_override( &self, locale: &str, key: impl Into<String>, value: impl Into<String>, )
Set a single override entry (#532) without a full reload — used by the admin edit path so a save takes effect immediately.
Sourcepub fn clear_overrides(&self)
pub fn clear_overrides(&self)
Drop every DB override, falling back to the file catalogs (#532).
Sourcepub fn override_count(&self) -> usize
pub fn override_count(&self) -> usize
Total number of override entries across all locales (#532) — handy for diagnostics and the admin coverage panel.
Sourcepub fn from_directory(
dir: &Path,
default_locale: Locale,
) -> Result<Self, I18nError>
pub fn from_directory( dir: &Path, default_locale: Locale, ) -> Result<Self, I18nError>
Load every *.json file in dir as a locale catalog. The file
stem becomes the locale identifier (e.g. en.json → Locale::new("en")).
Of two spellings of one locale (pt_BR.json, pt-BR.json) the first
by name wins; the other is skipped with a warning.
Each file must contain a flat object of string→string entries.
§Errors
I18nError::Io when the dir can’t be read or a file is unreadable.
I18nError::Parse when a JSON file is malformed.
Sourcepub fn from_settings(settings: &I18nSettings) -> Result<Self, I18nError>
pub fn from_settings(settings: &I18nSettings) -> Result<Self, I18nError>
Build a Translator from a crate::config::I18nSettings.
Reads each locale_paths entry as a directory of
Gated behind the config feature since it consults the
loader’s typed sections.
<lang>.json catalogs, narrows the active set to
languages (if non-empty), and pins the default locale +
fallback chain.
# config/default.toml
[i18n]
default_locale = "en"
languages = ["en", "fr", "es"]
locale_paths = ["locales", "vendor/locales"]
fallback_chain = ["en"]let settings = rustango::config::load()?;
let translator = rustango::i18n::Translator::from_settings(&settings.i18n)?;Defaults when fields are unset:
default_locale = None→"en".languages = []→ every catalog discovered vialocale_pathsstays active.languagesand file stems match asLocales, sopt-BRloadspt_BR.json; a second spelling in one directory is skipped.locale_paths = []→ no directory scan; resulting translator has no registered catalogs (apps that build catalogs programmatically viaadd_localeskip the TOML path entirely).fallback_chain = []→ only the implicitexact-locale → base-language → default-locale → keychain applies.
§Errors
I18nError::Io / I18nError::Parse forwarded from any
locale_paths entry that fails to load. A missing directory
is treated as a hard error so deployment mistakes surface
immediately rather than silently producing an empty
translator.
Sourcepub fn gettext(&self, locale: &str, key: &str) -> String
pub fn gettext(&self, locale: &str, key: &str) -> String
gettext-shape alias for Self::translate: look up the key
in the supplied locale and return the translated string, or
the key itself when no translation is found. This is the raw
lookup, with no parameter substitution.
For interpolation use Self::translate or
Self::gettext_fmt, which accepts a placeholder map.
Sourcepub fn gettext_fmt(
&self,
locale: &str,
key: &str,
params: &[(&str, &str)],
) -> String
pub fn gettext_fmt( &self, locale: &str, key: &str, params: &[(&str, &str)], ) -> String
gettext-shape lookup with placeholder substitution. Same
substitution rules as Self::translate ({name} →
params["name"]): gettext_fmt(locale, "Hi, {name}", &[("name", &user.name)]).
Sourcepub fn pgettext(&self, locale: &str, context: &str, key: &str) -> String
pub fn pgettext(&self, locale: &str, context: &str, key: &str) -> String
gettext-shape pgettext(context, message) — context-
disambiguated translation. Identical keys with different
contexts can resolve to different translations. Issue #422.
Catalog key format: "<context>\u{4}<message>" (the same
(EOT) delimiter gettext uses internally). When
no context-prefixed entry exists, falls back to the bare
message lookup so the function degrades gracefully on
catalogs that haven’t yet been authored with contexts.
Sourcepub fn pgettext_fmt(
&self,
locale: &str,
context: &str,
key: &str,
params: &[(&str, &str)],
) -> String
pub fn pgettext_fmt( &self, locale: &str, context: &str, key: &str, params: &[(&str, &str)], ) -> String
gettext-shape pgettext with placeholder substitution.
Mirrors Self::gettext_fmt semantics.
Sourcepub fn ngettext(
&self,
locale: &str,
singular: &str,
plural: &str,
count: i64,
) -> String
pub fn ngettext( &self, locale: &str, singular: &str, plural: &str, count: i64, ) -> String
gettext-shape ngettext(singular, plural, count) —
pluralization. Returns singular when count == 1,
plural otherwise.
Catalog format mirrors gettext’s msgid_plural convention:
register two keys, one for each form. The fallback chain is
the same as Self::translate; missing entries fall back
to the supplied source strings.
The plural form is selected by locale’s CLDR rule
(plural_category): the "one" category picks singular, every
other category picks plural. This is correct for two-form languages
(en/de: n == 1; fr: 0 and 1 are singular). Languages with three+
forms (Polish/Ukrainian few/many, Arabic’s six) can’t be fully
expressed with a singular/plural pair — use
Self::translate_plural with a per-category catalog for those (#1102).
count is bound to the {count} placeholder automatically
so templates can read "You have {count} unread messages"
without the caller threading it in.
Sourcepub fn ngettext_fmt(
&self,
locale: &str,
singular: &str,
plural: &str,
count: i64,
params: &[(&str, &str)],
) -> String
pub fn ngettext_fmt( &self, locale: &str, singular: &str, plural: &str, count: i64, params: &[(&str, &str)], ) -> String
Pluralization with additional placeholder substitution.
{count} is bound from the count argument; everything in
params overlays on top so callers can pass extra keys
({name}, {item}, etc.).
Auto Trait Implementations§
impl !Freeze for Translator
impl RefUnwindSafe for Translator
impl Send for Translator
impl Sync for Translator
impl Unpin for Translator
impl UnsafeUnpin for Translator
impl UnwindSafe for Translator
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
impl<A, B, T> HttpServerConnExec<A, B> for Twhere
B: Body,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more