Skip to main content

Text

Struct Text 

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

A translation shown later: the Rust counterpart of <i18n-t>.

Built by I18n::text, View::text or the t! macro, with options that mirror the component’s props. Nothing is looked up until it is shown: every Display resolves it again, so a Text kept in UI state follows set_locale and the scope it is shown in. 'static + Send + Sync + Clone.

use i18n_next::I18n;

let i18n = I18n::builder()
    .messages("en", None, r#"{"hi": "Hi, {name}!", "apples": "no apples | one apple | {count} apples"}"#)
    .messages("de", None, r#"{"hi": "Hallo, {name}!"}"#)
    .build()?;
let hi = i18n.text("hi").arg("name", "Ann");
assert_eq!(hi.to_string(), "Hi, Ann!");
i18n.set_locale("de")?;
assert_eq!(hi, "Hallo, Ann!");                       // the same value, the new locale
assert_eq!(i18n.text("apples").count(5).locale("en"), "5 apples");
assert_eq!(i18n.text("nope").or("Default").to_string(), "Default");
assert_eq!(i18n.text("nope").resolve(), None);       // a miss without a default

Resolution, as resolveText:

  • the key’s text in the locale and page (explicit on the Text, else the nearest scope’s, else the active locale and the root), interpolated with the arguments;
  • with count: the plural form tc picks, with {count};
  • with number: {number} is the number formatted in the text’s locale (tn), never escaped; the plural form and a custom rule are then not used (JS: the number prop wins over plural); date ({date}, td) and relative ({relativeDate}, tdr) the same, one of the three at a time, in that order of precedence;
  • a miss calls missing and shows the or default, else the key (both interpolated); a subtree shows the key;
  • html: text arguments are escaped (numbers and booleans are not), the translation is trusted, a key standing in for it is escaped;
  • hide_if_empty: blank text resolves to None and displays as the default (or nothing), as <i18n-t> renders it;
  • a Text argument without its own locale or page resolves in the outer one’s (and on its instance, when it has none); under html it is escaped unless it is html itself; missing is called once per display, for the outer and the inner alike;
  • nesting stops at 64 levels: a deeper Text argument is dropped, so its placeholder shows as written (showing, cloning and dropping never recurse deeper).

Display honours width, fill and precision ({:>8}, {:.2}), building the string first; without them it writes straight into the formatter.

Implementations§

Source§

impl Text

Source

pub fn arg( self, name: impl Into<Cow<'static, str>>, value: impl Into<Arg<'static>>, ) -> Self

Adds the value of {name} (JS params[name]): text, a number, a boolean, another Text. Up to four arguments are stored inline, without allocating.

Source

pub fn args<I>(self, items: I) -> Self
where I: IntoIterator, I::Item: Into<Arg<'static>>,

Adds positional values {0}, {1}… and {length} (a JS array as params).

Source

pub fn count(self, n: impl Into<Count>) -> Self

Picks the plural form for n and fills {count} (JS plural), as tc does.

Source

pub fn number(self, n: impl Into<Number>) -> Self

Fills {number} with n formatted in the text’s locale with the default options (JS <i18n-t :number>, tn(number)); not escaped under html. Set, it replaces the plural form: count and a custom rule are not used. Feature format.

use i18n_next::I18n;

let i18n = I18n::builder()
    .messages("en", None, r#"{"total": "Total: {number}"}"#)
    .messages("de", None, r#"{"total": "Summe: {number}"}"#)
    .build()?;
assert_eq!(i18n.text("total").number(1234.5), "Total: 1,234.5");
assert_eq!(i18n.text("total").number(1234.5).locale("de"), "Summe: 1.234,5");
Source

pub fn number_as( self, n: impl Into<Number>, name: impl Into<Cow<'static, str>>, ) -> Self

Text::number with the named format name of the text’s locale (I18n::tn_as); a missing name warns and formats with the defaults.

Source

pub fn date(self, t: impl Into<Timestamp>) -> Self

Fills {date} with t formatted in the text’s locale with the default options (JS <i18n-t :date>, td(date)); like number it replaces the plural form, and a number set as well wins (JS checks number first). Feature format.

use i18n_next::I18n;

let i18n = I18n::builder()
    .time_zone("UTC")
    .messages("en", None, r#"{"due": "Due {date}"}"#)
    .messages("de", None, r#"{"due": "Fällig am {date}"}"#)
    .build()?;
assert_eq!(i18n.text("due").date(1_704_428_640_000i64), "Due 1/5/2024");
assert_eq!(i18n.text("due").date(1_704_428_640_000i64).locale("de"), "Fällig am 5.1.2024");
Source

pub fn date_as( self, t: impl Into<Timestamp>, name: impl Into<Cow<'static, str>>, ) -> Self

Text::date with the named date format name of the text’s locale (I18n::td_as); a missing name warns and formats with the defaults.

Source

pub fn relative(self, t: impl Into<Timestamp>) -> Self

Fills {relativeDate} with t relative to the instance’s clock (JS <i18n-t :relative-date>, tdr(date)): 3 days ago. A number or date set as well wins. Feature format.

use i18n_next::I18n;

let now = 1_704_428_640_000i64;
let i18n = I18n::builder()
    .clock(move || now)
    .messages("en", None, r#"{"seen": "Seen {relativeDate}"}"#)
    .build()?;
assert_eq!(i18n.text("seen").relative(now - 120_000), "Seen 2 minutes ago");
Source

pub fn or(self, default: impl Into<Cow<'static, str>>) -> Self

The text shown on a miss (JS defaultValue), interpolated; empty counts as none.

Source

pub fn hide_if_empty(self) -> Self

Blank text resolves to None and displays as the default, or nothing (JS hideIfEmpty).

Source

pub fn plural_rule( self, rule: impl Fn(&PluralCtx<'_>) -> Option<String> + Send + Sync + 'static, ) -> Self

Replaces the plural rule (JS customPluralRule): with a count, the rule’s answer is the text as is (not interpolated); None is empty.

use i18n_next::I18n;

let i18n = I18n::builder().messages("en", None, r#"{"cats": "cat|cats"}"#).build()?;
let cats = i18n.text("cats").count(3).plural_rule(|c| {
    let forms = c.get(c.key);
    let mut it = forms.split('|');
    let form = if c.count == 1.0 { it.next() } else { it.nth(1) };
    form.map(|f| format!("{} {f}", c.count))
});
assert_eq!(cats.to_string(), "3 cats");
Source

pub fn page(self, name: impl Into<Cow<'static, str>>) -> Self

Reads this page (its layer, then the root), over any scope’s page.

Source

pub fn locale(self, code: impl Into<Cow<'static, str>>) -> Self

Resolves in this locale (as I18n::with_locale), over any scope’s locale.

Source

pub fn html(self) -> Self

The result goes into markup (JS html): text arguments are escaped, the translation is not; a key standing in for a missing translation is.

Source

pub fn resolve(&self) -> Option<String>

The text, None when the key is missing (or a subtree) and there is no default, or when hide_if_empty hides it. One allocation.

Source

pub fn to_string(&self) -> String

The displayed text in one allocation: what Display writes, sized first.

Source

pub fn write_to(&self, out: &mut impl Write) -> Result

Appends the displayed text to out (what Display writes), allocating nothing.

§Errors

Only what out returns.

Source

pub fn parts(&self) -> impl Iterator<Item = Part<'static>> + use<>

The template in pieces for rich text: runs of text (arguments filled in) and Part::Slots for placeholders no argument fills.

use i18n_next::{I18n, Part};

let i18n = I18n::builder().messages("en", None, r#"{"terms": "I accept the {link}, {who}"}"#).build()?;
let parts: Vec<Part> = i18n.text("terms").arg("who", "Ann").parts().collect();
assert_eq!(parts, [Part::Text("I accept the ".into()), Part::Slot("link".into()), Part::Text(", Ann".into())]);
Source

pub fn fold<T>( &self, text: impl FnMut(&str) -> T, slots: &[(&str, &dyn Fn() -> T)], ) -> Vec<T>

Folds the template into your own nodes (JS foldTemplate): a placeholder with a slot becomes the slot’s node; else its argument, else the placeholder as written, joins the surrounding text, which text turns into a node. Empty runs are skipped.

use i18n_next::I18n;

let i18n = I18n::builder().messages("en", None, r#"{"terms": "I accept the {link}."}"#).build()?;
let nodes = i18n.text("terms").fold(|t| format!("<{t}>"), &[("link", &|| "[terms]".to_owned())]);
assert_eq!(nodes, ["<I accept the >", "[terms]", "<.>"]);

Trait Implementations§

Source§

impl Clone for Text

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for Text

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Text

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl From<Text> for Arg<'_>

Source§

fn from(t: Text) -> Self

Converts to this type from the input type.
Source§

impl PartialEq<&str> for Text

Compares the displayed text, without building it.

Source§

fn eq(&self, other: &&str) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<Text> for &str

Source§

fn eq(&self, other: &Text) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<str> for Text

Source§

fn eq(&self, other: &str) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Text

§

impl !UnwindSafe for Text

§

impl Forget for Text

§

impl Freeze for Text

§

impl Move for Text

§

impl Send for Text

§

impl Sync for Text

§

impl Unpin for Text

§

impl UnsafeUnpin for Text

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.

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> 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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
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.