Skip to main content

I18n

Struct I18n 

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

The main handle for accessing and managing internationalization state.

I18n holds the selected language, fallback language, locale resources, and the active Fluent bundle used for translating messages. It is Clone + Copy so it can be freely passed around in components.

There are several ways to obtain an I18n instance:

Implementations§

Source§

impl I18n

Source

pub fn try_get() -> Option<Self>

Try to retrieve the I18n instance from the component context.

Returns None if no I18n has been provided via use_init_i18n or use_share_i18n in an ancestor component.

Source

pub fn get() -> Self

Retrieve the I18n instance from the component context.

This is the primary way to access the i18n state from within a component that is a descendant of a component that called use_init_i18n or use_share_i18n.

§Panics

Panics if no I18n has been provided in an ancestor component.

#[derive(PartialEq)]
struct MyComponent;

impl Component for MyComponent {
    fn render(&self) -> impl IntoElement {
        let mut i18n = I18n::get();

        let change_to_english = move |_| i18n.set_language(langid!("en-US"));

        rect()
            .child(t!("hello_world"))
            .child(Button::new().on_press(change_to_english).child("English"))
    }
}
Source

pub fn create(_: I18nConfig) -> Result<Self, Error>

Manually create an I18n instance from an I18nConfig.

Unlike use_init_i18n, this does not automatically provide the instance to descendant components. Use use_share_i18n to share it afterwards, or call this when you need explicit error handling during initialization.

The created state is scoped to the current component. For global state that outlives any single component, see I18n::create_global.

Source

pub fn create_global(_: I18nConfig) -> Result<Self, Error>

Create an I18n instance with global lifetime.

Unlike I18n::create, the state created here is not scoped to any component and will live for the entire duration of the application. This is useful for multi-window apps where i18n state needs to be created in main and then shared across different windows via use_share_i18n.

This is not a hook, do not use it inside components like you would use_init_i18n. You would usually want to call this in your main function.

struct MyApp {
    i18n: I18n,
}

impl App for MyApp {
    fn render(&self) -> impl IntoElement {
        // Re-provide the global I18n to this window's component tree
        use_share_i18n(move || self.i18n);

        rect().child(t!("hello_world"))
    }
}

fn main() {
    // Create I18n with global lifetime in main, before any window is opened
    let i18n = I18n::create_global(I18nConfig::new(langid!("en-US")).with_locale((
        langid!("en-US"),
        include_str!("../../../examples/i18n/en-US.ftl"),
    )))
    .expect("Failed to create I18n");

    // Pass it to each window's app struct
    launch(LaunchConfig::new().with_window(WindowConfig::new_app(MyApp { i18n })))
}
Source

pub fn try_translate_with_args( &self, msg: &str, args: Option<&FluentArgs<'_>>, ) -> Result<String, Error>

Translate a message by its identifier, optionally with Fluent arguments.

The msg can be a simple message id (e.g. "hello") or a dotted attribute id (e.g. "my_component.placeholder"). See I18n::decompose_identifier for details.

Returns an error if the message id is not found, the pattern is missing, or Fluent reports errors during formatting.

Prefer the t!, te!, or tid! macros for ergonomic translations.

Source

pub fn decompose_identifier(msg: &str) -> Result<(&str, Option<&str>), Error>

Split a message identifier into its message id and optional attribute name.

  • "hello" returns ("hello", None)
  • "my_component.placeholder" returns ("my_component", Some("placeholder"))

Returns an error if the identifier contains more than one dot.

Source

pub fn translate_with_args( &self, msg: &str, args: Option<&FluentArgs<'_>>, ) -> String

Translate a message by its identifier, optionally with Fluent arguments.

This is the panicking version of I18n::try_translate_with_args.

§Panics

Panics if the translation fails for any reason.

Source

pub fn try_translate(&self, msg: &str) -> Result<String, Error>

Translate a message by its identifier, without arguments.

Shorthand for self.try_translate_with_args(msg, None).

Source

pub fn translate(&self, msg: &str) -> String

Translate a message by its identifier, without arguments.

This is the panicking version of I18n::try_translate.

§Panics

Panics if the translation fails for any reason.

Source

pub fn language(&self) -> LanguageIdentifier

Get the selected language.

Source

pub fn fallback_language(&self) -> Option<LanguageIdentifier>

Get the fallback language.

Source

pub fn try_set_language(&mut self, id: LanguageIdentifier) -> Result<(), Error>

Update the selected language, rebuilding the active Fluent bundle.

Returns an error if the bundle cannot be rebuilt for the new language.

Source

pub fn set_language(&mut self, id: LanguageIdentifier)

Update the selected language, rebuilding the active Fluent bundle.

This is the panicking version of I18n::try_set_language.

§Panics

Panics if the bundle cannot be rebuilt for the new language.

Source

pub fn try_set_fallback_language( &mut self, id: LanguageIdentifier, ) -> Result<(), Error>

Update the fallback language, rebuilding the active Fluent bundle.

The given language must have a corresponding Locale registered in the config. Returns an error if no locale exists for the language or if the bundle cannot be rebuilt.

Source

pub fn set_fallback_language(&mut self, id: LanguageIdentifier)

Update the fallback language, rebuilding the active Fluent bundle.

This is the panicking version of I18n::try_set_fallback_language.

§Panics

Panics if no locale exists for the language or if the bundle cannot be rebuilt.

Trait Implementations§

Source§

impl Clone for I18n

Source§

fn clone(&self) -> I18n

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for I18n

Auto Trait Implementations§

§

impl Freeze for I18n

§

impl !RefUnwindSafe for I18n

§

impl !Send for I18n

§

impl !Sync for I18n

§

impl Unpin for I18n

§

impl UnsafeUnpin for I18n

§

impl !UnwindSafe for I18n

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<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

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

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

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
§

impl<T> IntoReadable<T> for T
where T: 'static,

§

fn into_readable(self) -> Readable<T>

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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