handlebars/decorators/
inline.rs
1use crate::context::Context;
2use crate::decorators::{DecoratorDef, DecoratorResult};
3use crate::error::RenderError;
4use crate::registry::Registry;
5use crate::render::{Decorator, RenderContext};
6use crate::RenderErrorReason;
7
8#[derive(Clone, Copy)]
9pub struct InlineDecorator;
10
11fn get_name<'reg: 'rc, 'rc>(d: &Decorator<'rc>) -> Result<String, RenderError> {
12 d.param(0)
13 .ok_or_else(|| RenderErrorReason::ParamNotFoundForIndex("inline", 0).into())
14 .and_then(|v| {
15 v.value()
16 .as_str()
17 .map(std::borrow::ToOwned::to_owned)
18 .ok_or_else(|| RenderErrorReason::InvalidParamType("String").into())
19 })
20}
21
22impl DecoratorDef for InlineDecorator {
23 fn call<'reg: 'rc, 'rc>(
24 &self,
25 d: &Decorator<'rc>,
26 _: &'reg Registry<'reg>,
27 _: &'rc Context,
28 rc: &mut RenderContext<'reg, 'rc>,
29 ) -> DecoratorResult {
30 let name = get_name(d)?;
31
32 let template = d
33 .template()
34 .ok_or(RenderErrorReason::BlockContentRequired)?;
35
36 rc.set_partial(name, template);
37 Ok(())
38 }
39}
40
41pub static INLINE_DECORATOR: InlineDecorator = InlineDecorator;
42
43#[cfg(test)]
44mod test {
45 use crate::context::Context;
46 use crate::registry::Registry;
47 use crate::render::{Evaluable, RenderContext};
48 use crate::template::Template;
49
50 #[test]
51 fn test_inline() {
52 let t0 =
53 Template::compile("{{#*inline \"hello\"}}the hello world inline partial.{{/inline}}")
54 .ok()
55 .unwrap();
56
57 let hbs = Registry::new();
58
59 let ctx = Context::null();
60 let mut rc = RenderContext::new(None);
61 t0.elements[0].eval(&hbs, &ctx, &mut rc).unwrap();
62
63 assert!(rc.get_partial("hello").is_some());
64 }
65}