projectfluent / fluent-rs

Rust implementation of Project Fluent
https://projectfluent.org
Apache License 2.0
1.07k stars 96 forks source link

Fluent.NumberArgument in fluent-rs #154

Closed mocsy closed 4 years ago

mocsy commented 4 years ago

What is the correct way to format values with currencies with fluent-rs? Is there an equivalent to Fluent.NumberArgument?

// main.js:
data = {
  amount: Fluent.NumberArgument(value, { currency: "USD" })
}

// main.ftl:
amount-owed = You owe { $amount }
  1. https://github.com/projectfluent/fluent/wiki/Fluent-and-ICU-MessageFormat#developer-driven
zbraniecki commented 4 years ago

Hi @mocsy!

Fluent-rs unfortunately doesn't handle all the ECMA402 functionality that JS side does yet.

The main reason is that Rust community did not develop equivalents of Intl.NumberFormat and Intl.DateTimeFormat just yet. There's an effort and I'm working on the https://github.com/zbraniecki/unic-datetime but it'll take a bit before we get there.

For now, if you work with Rust, I just landed a bunch of fixes that enable custom types and custom formatters to work, and also improve handling of Numbers.

I'll have to finish that over the next week or so, but you should be able to end up with sth like:

let mut args = FluentArgs::new();
args.insert("amount", FluentNumber(value, FluentNumberOptions {
    currency: "USD",
    Default::default()
}).into());

and then, you can do:

bundle.set_formatter(|arg| {
    if let FluentValue::Number(FluentNumber(val, options)) = arg {
        // needs to do more to check if the currency is set and adjust the pattern
        // to locale - basically need to write your own locale aware formatter
        Some(format!("{} {}", val, options.currency).into())
    } else {
        None
    }
});