fluent-handlebars-runtime 0.1.0

Runtime variable substitution in Handlebars using Fluent templates
Documentation

Fluent Handlebars runtime helper: An extension crate for Fluent Templates

The fluent_templates crate includes a helper for the Handlebars template framework that lets you provide values for Fluent placeables at build time. fluent-handlebars-runtime adds a helper that resolves placeables using the data hash you pass into the Handlebars render_template method.

For example, if your FTL files look like this:

# /resources/locale/en-US/app.ftl
into-place = One does not simply walk into {$place}

# /resources/locale/fr/app.ftl
into-place = On ne marche pas simplement à {$place}

You can then pass the replacement values at runtime:

# use handlebars::Handlebars;
# use fluent_handlebars_runtime::FluentHandlebars;
# use fluent_templates::ArcLoader;
# use unic_langid::langid;
# let loader = ArcLoader::builder(
#     "resources/locales",
#     langid!("en-US"),
# )
#     .customize(|b| b.set_use_isolating(false))
#     .build()
#     .unwrap();
#
let data = serde_json::json!({
"lang": "en-US",
"place": "Mordor"
});

let mut handlebars = Handlebars::new();
handlebars.register_helper("t", Box::from(FluentHandlebars::new(&loader)));
assert_eq!(
format!("{}", handlebars.render_template(r#"{{t "into-place"}}"#, &data).unwrap()),
"One does not simply walk into Mordor"
);

let data = serde_json::json!({
"lang": "fr",
"place": "Mordor"
});

assert_eq!(
format!("{}", handlebars.render_template(r#"{{t "into-place"}}"#, &data).unwrap()),
"On ne marche pas simplement à Mordor"
);

This allows you to substitute values into your localized strings that can only be known at runtime.

By convention, we call this helper "t" in the interest of keeping templates terse, but you can use a more verbose identifier (e.g. "translate" or "localize") if you find that more readable.

# use handlebars::Handlebars;
# use fluent_handlebars_runtime::FluentHandlebars;
# use fluent_templates::ArcLoader;
# use unic_langid::langid;
# let loader = ArcLoader::builder(
#     "resources/locales",
#     langid!("en-US"),
# )
#     .customize(|b| b.set_use_isolating(false))
#     .build()
#     .unwrap();
#
# let data = serde_json::json!({
#    "lang": "en-US",
#    "place": "Mordor"
# });
#
# let mut handlebars = Handlebars::new();
handlebars.register_helper("translate", Box::from(FluentHandlebars::new(&loader)));
assert_eq!(
format!("{}",
handlebars.render_template(r#"{{translate "into-place"}}"#, &data).unwrap()
),
"One does not simply walk into Mordor"
);