use std::error::Error; use handbar::{handbar_helper, Handbar, JsonRender}; use serde_json::{json, Value}; use time::format_description::parse; use time::OffsetDateTime; // define a helper using helper // a date format helper accept an `OffsetDateTime` as parameter handbar_helper!(date: |dt: OffsetDateTime| dt.format(&parse("[year]-[month]-[day]").unwrap()).unwrap()); // a helper returns number of provided parameters handbar_helper!(nargs: |*args| args.len()); // a helper joins all values, using both hash and parameters handbar_helper!(join: |{sep:str=","}, *args| args.iter().map(|a| a.render()).collect::>().join(sep) ); handbar_helper!(isdefined: |v: Value| !v.is_null()); // a helper provides format handbar_helper!(date2: |dt: OffsetDateTime, {fmt:str = "[year]-[month]-[day]"}| dt.format(&parse(fmt).unwrap()).unwrap() ); fn main() -> Result<(), Box> { // create the handbar registry let mut handbar = Handbar::new(); handbar.register_helper("date", Box::new(date)); handbar.register_helper("date2", Box::new(date2)); handbar.register_helper("nargs", Box::new(nargs)); handbar.register_helper("join", Box::new(join)); handbar.register_helper("isdefined", Box::new(isdefined)); let data = OffsetDateTime::now_utc(); println!("{}", handbar.render_template("{{date this}}", &data)?); println!("{}", handbar.render_template("{{date2 this}}", &data)?); println!( "{}", handbar.render_template("{{date2 this fmt=\"[day]/[month]/[year]\"}}", &data)? ); println!("{}", handbar.render_template("{{nargs 1 2 3 4}}", &())?); println!( "{}", handbar.render_template("{{join 1 2 3 4 sep=\"|\" }}", &())? ); println!( "{}", handbar.render_template( r#"{{isdefined a}} {{isdefined b}} {{#if (isdefined a)}}a{{/if}} {{#if (isdefined b)}}b{{/if}}"#, &json!({"a": 1}) )? ); Ok(()) }