Skip to content

Commit ac5bd3c

Browse files
committed
test: add example for testing value in helper macro #516
1 parent bfddca7 commit ac5bd3c

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

examples/helper_macro.rs

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
use std::error::Error;
22

3-
use handlebars::JsonRender;
4-
5-
use handlebars::{handlebars_helper, Handlebars};
3+
use handlebars::{handlebars_helper, Handlebars, JsonRender};
4+
use serde_json::{json, Value};
65
use time::format_description::parse;
76
use time::OffsetDateTime;
87

@@ -18,6 +17,8 @@ handlebars_helper!(join: |{sep:str=","}, *args|
1817
args.iter().map(|a| a.render()).collect::<Vec<String>>().join(sep)
1918
);
2019

20+
handlebars_helper!(isdefined: |v: Value| !v.is_null());
21+
2122
// a helper provides format
2223
handlebars_helper!(date2: |dt: OffsetDateTime, {fmt:str = "[year]-[month]-[day]"}|
2324
dt.format(&parse(fmt).unwrap()).unwrap()
@@ -31,6 +32,7 @@ fn main() -> Result<(), Box<dyn Error>> {
3132
handlebars.register_helper("date2", Box::new(date2));
3233
handlebars.register_helper("nargs", Box::new(nargs));
3334
handlebars.register_helper("join", Box::new(join));
35+
handlebars.register_helper("isdefined", Box::new(isdefined));
3436

3537
let data = OffsetDateTime::now_utc();
3638

@@ -48,5 +50,14 @@ fn main() -> Result<(), Box<dyn Error>> {
4850
handlebars.render_template("{{join 1 2 3 4 sep=\"|\" }}", &())?
4951
);
5052

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+
5162
Ok(())
5263
}

0 commit comments

Comments
 (0)