Debian Codegraph @

examples/helper_macro.rs

raw symbols SCIP
1 use std::error::Error;
2
3 use handlebars::{handlebars_helper, Handlebars, JsonRender};
4 use serde_json::{json, Value};
5 use time::format_description::parse;
6 use time::OffsetDateTime;
7
8 // define a helper using helper
9 // a date format helper accept an `OffsetDateTime` as parameter
10 handlebars_helper!(date: |dt: OffsetDateTime| dt.format(&parse("[year]-[month]-[day]").unwrap()).unwrap());
11
12 // a helper returns number of provided parameters
13 handlebars_helper!(nargs: |*args| args.len());
14
15 // a helper joins all values, using both hash and parameters
16 handlebars_helper!(join: |{sep:str=","}, *args|
17 args.iter().map(|a| a.render()).collect::<Vec<String>>().join(sep)
18 );
19
20 handlebars_helper!(isdefined: |v: Value| !v.is_null());
21
22 // a helper provides format
23 handlebars_helper!(date2: |dt: OffsetDateTime, {fmt:str = "[year]-[month]-[day]"}|
24 dt.format(&parse(fmt).unwrap()).unwrap()
25 );
26
27 fn main() -> Result<(), Box<dyn Error>> {
28 // create the handlebars registry
29 let mut handlebars = Handlebars::new();
30
31 handlebars.register_helper("date", Box::new(date));
32 handlebars.register_helper("date2", Box::new(date2));
33 handlebars.register_helper("nargs", Box::new(nargs));
34 handlebars.register_helper("join", Box::new(join));
35 handlebars.register_helper("isdefined", Box::new(isdefined));
36
37 let data = OffsetDateTime::now_utc();
38
39 println!("{}", handlebars.render_template("{{date this}}", &data)?);
40 println!("{}", handlebars.render_template("{{date2 this}}", &data)?);
41 println!(
42 "{}",
43 handlebars.render_template("{{date2 this fmt=\"[day]/[month]/[year]\"}}", &data)?
44 );
45
46 println!("{}", handlebars.render_template("{{nargs 1 2 3 4}}", &())?);
47
48 println!(
49 "{}",
50 handlebars.render_template("{{join 1 2 3 4 sep=\"|\" }}", &())?
51 );
52
53 println!(
54 "{}",
55 handlebars.render_template(
56 r#"{{isdefined a}} {{isdefined b}}
57 {{#if (isdefined a)}}a{{/if}} {{#if (isdefined b)}}b{{/if}}"#,
58 &json!({"a": 1})
59 )?
60 );
61
62 Ok(())
63 }