#handlebars #fluent #localization

handlebars-fluent

Handlebars helpers for the Fluent internationalization framework

6 releases (3 breaking)

0.4.0 Jan 15, 2024
0.3.2 Apr 12, 2023
0.3.0 Feb 20, 2020
0.2.0 Dec 6, 2019
0.1.0 Nov 7, 2019

#240 in Template engine

33 downloads per month

MIT/Apache

23KB
386 lines

handlebars-fluent

Build Status Current Version License: MIT/Apache-2.0

This crate provides the Rust implementation¹ of Handlebars with a helper for the Fluent internationalization framework.

¹ See handlebars-helper-fluent for a Fluent helper for the Javascript implementation of Handlebars.


lib.rs:

Fluent helper for Handlebars.

This crate provides a Handlebars helper that can load Fluent strings.

Setting up the fluent helper with handlebars

The easiest way to use this is to use the simple_loader!() macro:

use handlebars_fluent::*;
use handlebars::*;
use serde_json::*;

simple_loader!(create_loader, "./locales/", "en-US");

fn init(handlebars: &mut Handlebars) {
    let loader = create_loader();
    let helper = FluentHelper::new(loader);
    handlebars.register_helper("fluent", Box::new(helper));
}

fn render_page(handlebars: &Handlebars) -> String {
    let data = json!({"lang": "zh-CN"});
    handlebars.render_template("{{fluent \"foo-bar\"}} baz", &data).unwrap()
}

You should have a locales/ folder somewhere with one folder per language code, containing all of your FTL files. See the simple_loader!() macro for more options.

Make sure the handlebars::Context has a toplevel "lang" field when rendering.

Using the fluent helper in your templates

The main helper provided is the {{fluent}} helper. If you have the following Fluent file:

foo-bar = "foo bar"
placeholder = this has a placeholder { $variable }

You can include the strings in your template with

{{fluent "foo-bar"}} <!-- will render "foo bar" -->
{{fluent "placeholder" variable="baz"}} <!-- will render "this has a placeholder baz" -->

You may also use the {{fluentparam}} helper to specify variables, especially if you need them to be multiline, like so:

{{#fluent "placeholder"}}
    {{#fluentparam "variable"}}
        first line
        second line
    {{/fluentparam}}
{{/fluent}}

Multiple {{fluentparam}}s may be specified

Dependencies

~6MB
~123K SLoC