Skip to main content

Translator

Struct Translator 

Source
pub struct Translator { /* private fields */ }
Expand description

Translation backend — keyed by (locale, key).

Implementations§

Source§

impl Translator

Source

pub fn new(default_locale: Locale) -> Self

New translator with the given fallback locale.

Source

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).

Source

pub fn fallback_chain(&self) -> &[Locale]

Current explicit fallback chain (without the implicit default-locale terminus). Useful for diagnostics.

Source

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.

Source

pub fn insert_locale(&self, locale: Locale, catalog: HashMap<String, String>)

Mutably add a catalog (use with let mut t = ...).

Source

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.

Source

pub fn insert_plural_locale( &self, locale: Locale, catalog: HashMap<String, HashMap<String, String>>, )

Mutably add a plural catalog (use with let mut t = ...).

Source

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.

Source

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."
Source

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.

Source

pub fn locales(&self) -> Vec<String>

All registered locale identifiers (for negotiate_language).

Source

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).

Source

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.

Source

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.

Source

pub fn clear_overrides(&self)

Drop every DB override, falling back to the file catalogs (#532).

Source

pub fn override_count(&self) -> usize

Total number of override entries across all locales (#532) — handy for diagnostics and the admin coverage panel.

Source

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.

Source

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 via locale_paths stays active.
  • languages and file stems match as Locales, so pt-BR loads pt_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 via add_locale skip the TOML path entirely).
  • fallback_chain = [] → only the implicit exact-locale → base-language → default-locale → key chain 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.

Source

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.

Source

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)]).

Source

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.

Source

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.

Source

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.

Source

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§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more