Skip to content

Commit

Permalink
chore: update example for helper macro
Browse files Browse the repository at this point in the history
  • Loading branch information
sunng87 committed Jul 7, 2022
1 parent 8af9de9 commit a8f4875
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions examples/helper_macro.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::error::Error;

use handlebars::JsonRender;

use handlebars::{handlebars_helper, Handlebars};
use time::format_description::parse;
use time::OffsetDateTime;
Expand All @@ -11,6 +13,11 @@ handlebars_helper!(date: |dt: OffsetDateTime| dt.format(&parse("[year]-[month]-[
// a helper returns number of provided parameters
handlebars_helper!(nargs: |*args| args.len());

// a helper joins all values, using both hash and parameters
handlebars_helper!(join: |{sep:str=","}, *args|
args.iter().map(|a| a.render()).collect::<Vec<String>>().join(sep)
);

// a helper provides format
handlebars_helper!(date2: |dt: OffsetDateTime, {fmt:str = "[year]-[month]-[day]"}|
dt.format(&parse(fmt).unwrap()).unwrap()
Expand All @@ -23,6 +30,7 @@ fn main() -> Result<(), Box<dyn Error>> {
handlebars.register_helper("date", Box::new(date));
handlebars.register_helper("date2", Box::new(date2));
handlebars.register_helper("nargs", Box::new(nargs));
handlebars.register_helper("join", Box::new(join));

let data = OffsetDateTime::now_utc();

Expand All @@ -35,5 +43,10 @@ fn main() -> Result<(), Box<dyn Error>> {

println!("{}", handlebars.render_template("{{nargs 1 2 3 4}}", &())?);

println!(
"{}",
handlebars.render_template("{{join 1 2 3 4 sep=\"|\" }}", &())?
);

Ok(())
}

0 comments on commit a8f4875

Please sign in to comment.