Skip to main content

t

Macro t 

Source
macro_rules! t {
    ($key:literal) => { ... };
    ($key:literal, { $($k:expr => $v:expr),* $(,)? }) => { ... };
    ($key:expr) => { ... };
    ($key:expr, { $($k:expr => $v:expr),* $(,)? }) => { ... };
}
Expand description

The primary accessor macro for localized strings.

It looks the key up in the active language (see set_lang) using the crate’s generated CATALOG (which carries its configured fallback locale and its locale negotiation aliases). Without arguments it returns Cow::Borrowed for static messages; with arguments the message is formatted with them (static messages still return without allocating).

§Compile-time key checking

A string literal key is checked at compile time against every message ID the build script found in any locale, so a typo such as t!("app-titel") fails the build instead of showing the raw key on screen. The check runs in a const item and adds nothing at run time. Keys given as any other expression (a variable, a constant such as the generated keys::APP_TITLE) are not checked by the macro; the generated keys:: constants are checked by the compiler simply by existing. To pass a key that is deliberately not defined in any locale, bind it to a variable or constant first.

The macro resolves crate::CATALOG and crate::__FLUENT_ZERO_KEYS, so the crate calling it must include! the file generated by fluent-zero-build at its root.

§Examples

use fluent_zero::t;

// Basic usage:
let title = t!("app-title");
assert_eq!(title, "My App");

// With arguments:
let welcome = t!("welcome-user", {
    "name" => "Alice",
    "unread_count" => 5
});
assert_eq!(welcome, "Welcome, Alice! (5 unread)");

// Attributes use the `message.attribute` key:
let tooltip = t!("login.tooltip");
assert_eq!(tooltip, "Sign in to your account");

// A missing key returns the key itself. (A literal unknown key would not
// compile, so it goes through a variable.)
let missing = "no-such-message";
assert_eq!(t!(missing), "no-such-message");