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 defaultResolution, 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 formtcpicks, 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: thenumberprop wins overplural);date({date},td) andrelative({relativeDate},tdr) the same, one of the three at a time, in that order of precedence; - a miss calls
missingand shows theordefault, 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 toNoneand displays as the default (or nothing), as<i18n-t>renders it;- a
Textargument without its own locale or page resolves in the outer one’s (and on its instance, when it has none); underhtmlit is escaped unless it ishtmlitself;missingis called once per display, for the outer and the inner alike; - nesting stops at 64 levels: a deeper
Textargument 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
impl Text
Sourcepub fn arg(
self,
name: impl Into<Cow<'static, str>>,
value: impl Into<Arg<'static>>,
) -> Self
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.
Sourcepub fn args<I>(self, items: I) -> Self
pub fn args<I>(self, items: I) -> Self
Adds positional values {0}, {1}… and {length} (a JS array as params).
Sourcepub fn count(self, n: impl Into<Count>) -> Self
pub fn count(self, n: impl Into<Count>) -> Self
Picks the plural form for n and fills {count} (JS plural), as tc does.
Sourcepub fn number(self, n: impl Into<Number>) -> Self
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");Sourcepub fn number_as(
self,
n: impl Into<Number>,
name: impl Into<Cow<'static, str>>,
) -> Self
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.
Sourcepub fn date(self, t: impl Into<Timestamp>) -> Self
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");Sourcepub fn date_as(
self,
t: impl Into<Timestamp>,
name: impl Into<Cow<'static, str>>,
) -> Self
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.
Sourcepub fn relative(self, t: impl Into<Timestamp>) -> Self
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");Sourcepub fn or(self, default: impl Into<Cow<'static, str>>) -> Self
pub fn or(self, default: impl Into<Cow<'static, str>>) -> Self
The text shown on a miss (JS defaultValue), interpolated; empty counts as none.
Sourcepub fn hide_if_empty(self) -> Self
pub fn hide_if_empty(self) -> Self
Blank text resolves to None and displays as the default, or nothing (JS
hideIfEmpty).
Sourcepub fn plural_rule(
self,
rule: impl Fn(&PluralCtx<'_>) -> Option<String> + Send + Sync + 'static,
) -> Self
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");Sourcepub fn page(self, name: impl Into<Cow<'static, str>>) -> Self
pub fn page(self, name: impl Into<Cow<'static, str>>) -> Self
Reads this page (its layer, then the root), over any scope’s page.
Sourcepub fn locale(self, code: impl Into<Cow<'static, str>>) -> Self
pub fn locale(self, code: impl Into<Cow<'static, str>>) -> Self
Resolves in this locale (as I18n::with_locale), over any scope’s locale.
Sourcepub fn html(self) -> Self
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.
Sourcepub fn resolve(&self) -> Option<String>
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.
Sourcepub fn to_string(&self) -> String
pub fn to_string(&self) -> String
The displayed text in one allocation: what Display writes, sized first.
Sourcepub fn write_to(&self, out: &mut impl Write) -> Result
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.
Sourcepub fn parts(&self) -> impl Iterator<Item = Part<'static>> + use<>
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())]);Sourcepub fn fold<T>(
&self,
text: impl FnMut(&str) -> T,
slots: &[(&str, &dyn Fn() -> T)],
) -> Vec<T>
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]", "<.>"]);