From b176776136f07d19ae3d8ce5678ffb25ff609bc4 Mon Sep 17 00:00:00 2001 From: Christian Schwarz Date: Sun, 30 Jun 2024 03:26:17 +0200 Subject: [PATCH] add let helper as an example --- examples/block_helper_macro_let.rs | 65 ++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 examples/block_helper_macro_let.rs diff --git a/examples/block_helper_macro_let.rs b/examples/block_helper_macro_let.rs new file mode 100644 index 000000000..7ebf53e29 --- /dev/null +++ b/examples/block_helper_macro_let.rs @@ -0,0 +1,65 @@ +use handlebars::{ + BlockParamHolder, Context, Handlebars, Helper, Output, RenderContext, RenderError, + RenderErrorReason, +}; +use serde_json::{json, Value}; + +// a custom block helper to bind a variable name to a value +pub fn helper_let<'reg, 'rc>( + h: &Helper<'rc>, + _r: &'reg Handlebars<'reg>, + _ctx: &'rc Context, + rc: &mut RenderContext<'reg, 'rc>, + _out: &mut dyn Output, +) -> Result<(), RenderError> { + let name_param = h + .param(0) + .ok_or_else(|| RenderErrorReason::ParamNotFoundForIndex("let", 0))?; + + let handlebars::ScopedJson::Constant(Value::String(name_constant)) = name_param.value else { + return Err(RenderErrorReason::ParamTypeMismatchForName( + "let", + "0".to_string(), + "constant string".to_string(), + ) + .into()); + }; + + let value = h + .param(1) + .as_ref() + .map(|v| v.value().to_owned()) + .ok_or_else(|| RenderErrorReason::ParamNotFoundForIndex("let", 2))?; + + let block = rc.block_mut().unwrap(); + + block.set_block_param(name_constant, BlockParamHolder::Value(value)); + + Ok(()) +} + +fn main() -> Result<(), RenderError> { + // create the handlebars registry + let mut handlebars = Handlebars::new(); + + handlebars.register_helper("let", Box::new(helper_let)); + + let input = r#" +{{#if foo}} +{{let "mixin_classes" "foo-bar baz"}} +{{else}} +{{let "mixin_classes" "quux"}} +{{/if}} + +
+

content

+
+"#; + + println!( + "{}", + handlebars.render_template(input, &json!({"foo": true}))? + ); + + Ok(()) +}