[][src]Struct fluent_bundle::bundle::FluentBundle

pub struct FluentBundle<'bundle> {
    pub locales: Vec<String>,
    pub entries: HashMap<String, Entry<'bundle>>,
    pub plural_rules: IntlPluralRules,
}

A collection of localization messages for a single locale, which are meant to be used together in a single view, widget or any other UI abstraction.

Examples

use fluent_bundle::{FluentBundle, FluentResource, FluentValue};
use std::collections::HashMap;

let ftl_string = String::from("intro = Welcome, { $name }.");
let resource = FluentResource::try_new(ftl_string)
    .expect("Could not parse an FTL string.");

let mut bundle = FluentBundle::new(&["en-US"]);
bundle.add_resource(&resource)
    .expect("Failed to add FTL resources to the bundle.");

let mut args = HashMap::new();
args.insert("name", FluentValue::from("Rustacean"));

let (value, _) = bundle.format("intro", Some(&args))
    .expect("Failed to format a message.");
assert_eq!(&value, "Welcome, Rustacean.");

FluentBundle Life Cycle

To create a bundle, call FluentBundle::new with a locale list that represents the best possible fallback chain for a given locale. The simplest case is a one-locale list.

Next, call add_resource one or more times, supplying translations in the FTL syntax. The FluentBundle instance is now ready to be used for localization.

To format a translation, call format with the path of a message or attribute in order to retrieve the translated string. Alternately, compound provides a convenient way of formatting all attributes of a message at once.

The result of format is an Option<T> wrapping a (String, Vec<FluentError>). On success, the string is a formatted value that should be displayed in the UI. It is recommended to treat the result as opaque from the perspective of the program and use it only to display localized messages. Do not examine it or alter in any way before displaying. This is a general good practice as far as all internationalization operations are concerned.

Locale Fallback Chain

FluentBundle stores messages in a single locale, but keeps a locale fallback chain for the purpose of language negotiation with i18n formatters. For instance, if date and time formatting are not available in the first locale, FluentBundle will use its locales fallback chain to negotiate a sensible fallback for date and time formatting.

Fields

locales: Vec<String>entries: HashMap<String, Entry<'bundle>>plural_rules: IntlPluralRules

Methods

impl<'bundle> FluentBundle<'bundle>[src]

pub fn new<'a, S: ToString>(locales: &'a [S]) -> FluentBundle<'bundle>[src]

Constructs a FluentBundle. locales is the fallback chain of locales to use for formatters like date and time. locales does not influence message selection.

Examples

use fluent_bundle::FluentBundle;

let mut bundle = FluentBundle::new(&["en-US"]);

Errors

This will panic if no formatters can be found for the locales.

pub fn has_message(&self, id: &str) -> bool[src]

Returns true if this bundle contains a message with the given id.

Examples

use fluent_bundle::{FluentBundle, FluentResource};

let ftl_string = String::from("hello = Hi!");
let resource = FluentResource::try_new(ftl_string)
    .expect("Failed to parse an FTL string.");
let mut bundle = FluentBundle::new(&["en-US"]);
bundle.add_resource(&resource)
    .expect("Failed to add FTL resources to the bundle.");
assert_eq!(true, bundle.has_message("hello"));

pub fn add_function<F>(&mut self, id: &str, func: F) -> Result<(), FluentError> where
    F: 'bundle + Fn(&[Option<FluentValue>], &HashMap<&str, FluentValue>) -> Option<FluentValue> + Sync + Send
[src]

Makes the provided rust function available to messages with the name id. See the FTL syntax guide to learn how these are used in messages.

FTL functions accept both positional and named args. The rust function you provide therefore has two parameters: a slice of values for the positional args, and a HashMap of values for named args.

Examples

use fluent_bundle::{FluentBundle, FluentResource, FluentValue};

let ftl_string = String::from("length = { STRLEN(\"12345\") }");
let resource = FluentResource::try_new(ftl_string)
    .expect("Could not parse an FTL string.");
let mut bundle = FluentBundle::new(&["en-US"]);
bundle.add_resource(&resource)
    .expect("Failed to add FTL resources to the bundle.");

// Register a fn that maps from string to string length
bundle.add_function("STRLEN", |positional, _named| match positional {
    [Some(FluentValue::String(str))] => Some(FluentValue::Number(str.len().to_string())),
    _ => None,
}).expect("Failed to add a function to the bundle.");

let (value, _) = bundle.format("length", None)
    .expect("Failed to format a message.");
assert_eq!(&value, "5");

pub fn add_resource(
    &mut self,
    res: &'bundle FluentResource
) -> Result<(), Vec<FluentError>>
[src]

Adds the message or messages, in FTL syntax, to the bundle, returning an empty Result<T> on success.

Examples

use fluent_bundle::{FluentBundle, FluentResource};

let ftl_string = String::from("
hello = Hi!
goodbye = Bye!
");
let resource = FluentResource::try_new(ftl_string)
    .expect("Could not parse an FTL string.");
let mut bundle = FluentBundle::new(&["en-US"]);
bundle.add_resource(&resource)
    .expect("Failed to add FTL resources to the bundle.");
assert_eq!(true, bundle.has_message("hello"));

Whitespace

Message ids must have no leading whitespace. Message values that span multiple lines must have leading whitespace on all but the first line. These are standard FTL syntax rules that may prove a bit troublesome in source code formatting. The indoc! crate can help with stripping extra indentation if you wish to indent your entire message.

pub fn format(
    &self,
    path: &str,
    args: Option<&HashMap<&str, FluentValue>>
) -> Option<(String, Vec<FluentError>)>
[src]

Formats the message value identified by path using args to provide variables. path is either a message id ("hello"), or message id plus attribute ("hello.tooltip").

Examples

use fluent_bundle::{FluentBundle, FluentResource, FluentValue};
use std::collections::HashMap;

let ftl_string = String::from("intro = Welcome, { $name }.");
let resource = FluentResource::try_new(ftl_string)
    .expect("Could not parse an FTL string.");
let mut bundle = FluentBundle::new(&["en-US"]);
bundle.add_resource(&resource)
    .expect("Failed to add FTL resources to the bundle.");

let mut args = HashMap::new();
args.insert("name", FluentValue::from("Rustacean"));

let (value, _) = bundle.format("intro", Some(&args))
    .expect("Failed to format a message.");
assert_eq!(&value, "Welcome, Rustacean.");

An example with attributes and no args:

use fluent_bundle::{FluentBundle, FluentResource};

let ftl_string = String::from("
hello =
    .title = Hi!
    .tooltip = This says 'Hi!'
");
let resource = FluentResource::try_new(ftl_string)
    .expect("Could not parse an FTL string.");
let mut bundle = FluentBundle::new(&["en-US"]);
bundle.add_resource(&resource)
    .expect("Failed to add FTL resources to the bundle.");

let (value, _) = bundle.format("hello.title", None)
    .expect("Failed to format a message.");
assert_eq!(&value, "Hi!");

Errors

For some cases where format can't find a message it will return None.

In all other cases format returns a string even if it encountered errors. Generally, during partial errors format will use '___' to replace parts of the formatted message that it could not successfuly build. For more fundamental errors format will return the path itself as the translation.

The second term of the tuple will contain any extra error information gathered during formatting. A caller may safely ignore the extra errors if the fallback formatting policies are acceptable.

use fluent_bundle::{FluentBundle, FluentResource};

// Create a message with bad cyclic reference
let ftl_string = String::from("foo = a { foo } b");
let resource = FluentResource::try_new(ftl_string)
    .expect("Could not parse an FTL string.");
let mut bundle = FluentBundle::new(&["en-US"]);
bundle.add_resource(&resource)
    .expect("Failed to add FTL resources to the bundle.");

// The result falls back to "___"
let (value, _) = bundle.format("foo", None)
    .expect("Failed to format a message.");
assert_eq!(&value, "___");

pub fn compound(
    &self,
    message_id: &str,
    args: Option<&HashMap<&str, FluentValue>>
) -> Option<(Message, Vec<FluentError>)>
[src]

Formats both the message value and attributes identified by message_id using args to provide variables. This is useful for cases where a UI element requires multiple related text fields, such as a button that has both display text and assistive text.

Examples

use fluent_bundle::{FluentBundle, FluentResource, FluentValue};
use std::collections::HashMap;

let ftl_string = String::from("
login-input = Predefined value
    .placeholder = example@email.com
    .aria-label = Login input value
    .title = Type your login email
");
let resource = FluentResource::try_new(ftl_string)
    .expect("Could not parse an FTL string.");
let mut bundle = FluentBundle::new(&["en-US"]);
bundle.add_resource(&resource)
    .expect("Failed to add FTL resources to the bundle.");

let (message, _) = bundle.compound("login-input", None)
    .expect("Failed to format a message.");
assert_eq!(message.value, Some("Predefined value".to_string()));
assert_eq!(message.attributes.get("title"), Some(&"Type your login email".to_string()));

Errors

For some cases where compound can't find a message it will return None.

In all other cases compound returns a message even if it encountered errors. Generally, during partial errors compound will use '___' to replace parts of the formatted message that it could not successfuly build. For more fundamental errors compound will return the path itself as the translation.

The second term of the tuple will contain any extra error information gathered during formatting. A caller may safely ignore the extra errors if the fallback formatting policies are acceptable.

Auto Trait Implementations

impl<'bundle> Send for FluentBundle<'bundle>

impl<'bundle> Sync for FluentBundle<'bundle>

Blanket Implementations

impl<T, U> Into for T where
    U: From<T>, 
[src]

impl<T> From for T[src]

impl<T, U> TryFrom for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T> Borrow for T where
    T: ?Sized
[src]

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> BorrowMut for T where
    T: ?Sized
[src]

impl<T, U> TryInto for T where
    U: TryFrom<T>, 
[src]

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

The type returned in the event of a conversion error.