Rust's built-ins already support compile-time formatting. But what if you have, say, a JSON containing language resources such as follows?
res/lang/en-us/_.json
{
"welcome": "Welcome, $p!"
}
I needed something simple to replace this $p
sequence, not a full-fledged template framework. I provided a handy utility which can optionally process its own arguments to the string parameters.
It looks a bit cryptic because arguments are Box<dyn Any>
.
use rialight_util::template_string;
fn main() {
// formatting (processor, the 3rd argument, is optional)
let applied = template_string::apply("$<foo-qux>", &template_string::map! { "foo-qux" => "Fq" }, None);
assert_eq!(applied, "Fq".to_owned());
let applied = template_string::apply("$<foo-qux>", &template_string::map! { "foo-qux" => "Fq" }, Some(|v| (*v.downcast_ref::<&'static str>().unwrap()).to_owned()));
assert_eq!(applied, "Fq".to_owned());
let applied = template_string::apply("$<foo-qux>", &template_string::map! {}, None);
assert_eq!(applied, "None".to_owned());
// constructing a template_string::Map
let map = template_string::map!{
"a" => "foo",
"b" => "bar",
};
assert_eq!(*map[&"a".to_owned()].downcast_ref::<&'static str>().unwrap(), "foo");
assert_eq!(*map[&"b".to_owned()].downcast_ref::<&'static str>().unwrap(), "bar");
assert!(map.get(&"c".to_owned()).is_none());
}
More information:
-
rialight_util::template_string::Map
is equivalent toHashMap<String, Box<dyn Any>>
. - formatting syntax:
$<person-name>
- formatting syntax:
$personname
(parameter without hyphens or underscores) - formatting syntax:
$$
(single dollar)
Here's the implementation: template_string.rs
It's available on crates.io:
[dependencies]
rialight_util = "1"