Trait handlebars::HelperDef

source ·
pub trait HelperDef {
    fn call_inner<'reg: 'rc, 'rc>(
        &self,
        _: &Helper<'reg, 'rc>,
        _: &'reg Registry<'reg>,
        _: &'rc Context,
        _: &mut RenderContext<'reg, 'rc>
    ) -> Result<ScopedJson<'reg, 'rc>, RenderError> { ... } fn call<'reg: 'rc, 'rc>(
        &self,
        h: &Helper<'reg, 'rc>,
        r: &'reg Registry<'reg>,
        ctx: &'rc Context,
        rc: &mut RenderContext<'reg, 'rc>,
        out: &mut dyn Output
    ) -> HelperResult { ... } }
Expand description

Helper Definition

Implement HelperDef to create custom helpers. You can retrieve useful information from these arguments.

  • &Helper: current helper template information, contains name, params, hashes and nested template
  • &Registry: the global registry, you can find templates by name from registry
  • &Context: the whole data to render, in most case you can use data from Helper
  • &mut RenderContext: you can access data or modify variables (starts with @)/partials in render context, for example, @index of #each. See its document for detail.
  • &mut dyn Output: where you write output to

By default, you can use a bare function as a helper definition because we have supported unboxed_closure. If you have stateful or configurable helper, you can create a struct to implement HelperDef.

Define an inline helper

use handlebars::*;

fn upper(h: &Helper<'_, '_>, _: &Handlebars<'_>, _: &Context, rc:
&mut RenderContext<'_, '_>, out: &mut dyn Output)
    -> HelperResult {
   // get parameter from helper or throw an error
   let param = h.param(0).and_then(|v| v.value().as_str()).unwrap_or("");
   out.write(param.to_uppercase().as_ref())?;
   Ok(())
}

Define block helper

Block helper is like #if or #each which has a inner template and an optional inverse template (the template in else branch). You can access the inner template by helper.template() and helper.inverse(). In most cases you will just call render on it.

use handlebars::*;

fn dummy_block<'reg, 'rc>(
    h: &Helper<'reg, 'rc>,
    r: &'reg Handlebars<'reg>,
    ctx: &'rc Context,
    rc: &mut RenderContext<'reg, 'rc>,
    out: &mut dyn Output,
) -> HelperResult {
    h.template()
        .map(|t| t.render(r, ctx, rc, out))
        .unwrap_or(Ok(()))
}

Define helper function using macro

In most cases you just need some simple function to call from templates. We have a handlebars_helper! macro to simplify the job.

use handlebars::*;

handlebars_helper!(plus: |x: i64, y: i64| x + y);

let mut hbs = Handlebars::new();
hbs.register_helper("plus", Box::new(plus));

Provided Methods§

A simplified api to define helper

To implement your own call_inner, you will return a new ScopedJson which has a JSON value computed from current context.

Calling from subexpression

When calling the helper as a subexpression, the value and its type can be received by upper level helpers.

Note that the value can be json!(null) which is treated as false in helpers like if and rendered as empty string.

Examples found in repository?
src/helpers/mod.rs (line 122)
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
    fn call<'reg: 'rc, 'rc>(
        &self,
        h: &Helper<'reg, 'rc>,
        r: &'reg Registry<'reg>,
        ctx: &'rc Context,
        rc: &mut RenderContext<'reg, 'rc>,
        out: &mut dyn Output,
    ) -> HelperResult {
        match self.call_inner(h, r, ctx, rc) {
            Ok(result) => {
                if r.strict_mode() && result.is_missing() {
                    Err(RenderError::strict_error(None))
                } else {
                    // auto escape according to settings
                    let output = do_escape(r, rc, result.render());
                    out.write(output.as_ref())?;
                    Ok(())
                }
            }
            Err(e) => {
                if e.is_unimplemented() {
                    // default implementation, do nothing
                    Ok(())
                } else {
                    Err(e)
                }
            }
        }
    }
More examples
Hide additional examples
src/render.rs (line 567)
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
fn call_helper_for_value<'reg: 'rc, 'rc>(
    hd: &dyn HelperDef,
    ht: &Helper<'reg, 'rc>,
    r: &'reg Registry<'reg>,
    ctx: &'rc Context,
    rc: &mut RenderContext<'reg, 'rc>,
) -> Result<PathAndJson<'reg, 'rc>, RenderError> {
    match hd.call_inner(ht, r, ctx, rc) {
        Ok(result) => Ok(PathAndJson::new(None, result)),
        Err(e) => {
            if e.is_unimplemented() {
                // parse value from output
                let mut so = StringOutput::new();

                // here we don't want subexpression result escaped,
                // so we temporarily disable it
                let disable_escape = rc.is_disable_escape();
                rc.set_disable_escape(true);

                hd.call(ht, r, ctx, rc, &mut so)?;
                rc.set_disable_escape(disable_escape);

                let string = so.into_string().map_err(RenderError::from)?;
                Ok(PathAndJson::new(
                    None,
                    ScopedJson::Derived(Json::String(string)),
                ))
            } else {
                Err(e)
            }
        }
    }
}

A complex version of helper interface.

This function offers Output, which you can write custom string into and render child template. Helpers like if and each are implemented with this. Because the data written into Output are typically without type information. So helpers defined by this function are not composable.

Calling from subexpression

Although helpers defined by this are not composable, when called from subexpression, handlebars tries to parse the string output as JSON to re-build its type. This can be buggy with numrical and other literal values. So it is not recommended to use these helpers in subexpression.

Examples found in repository?
src/render.rs (line 579)
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
fn call_helper_for_value<'reg: 'rc, 'rc>(
    hd: &dyn HelperDef,
    ht: &Helper<'reg, 'rc>,
    r: &'reg Registry<'reg>,
    ctx: &'rc Context,
    rc: &mut RenderContext<'reg, 'rc>,
) -> Result<PathAndJson<'reg, 'rc>, RenderError> {
    match hd.call_inner(ht, r, ctx, rc) {
        Ok(result) => Ok(PathAndJson::new(None, result)),
        Err(e) => {
            if e.is_unimplemented() {
                // parse value from output
                let mut so = StringOutput::new();

                // here we don't want subexpression result escaped,
                // so we temporarily disable it
                let disable_escape = rc.is_disable_escape();
                rc.set_disable_escape(true);

                hd.call(ht, r, ctx, rc, &mut so)?;
                rc.set_disable_escape(disable_escape);

                let string = so.into_string().map_err(RenderError::from)?;
                Ok(PathAndJson::new(
                    None,
                    ScopedJson::Derived(Json::String(string)),
                ))
            } else {
                Err(e)
            }
        }
    }
}

impl Parameter {
    pub fn expand_as_name<'reg: 'rc, 'rc>(
        &'reg self,
        registry: &'reg Registry<'reg>,
        ctx: &'rc Context,
        rc: &mut RenderContext<'reg, 'rc>,
    ) -> Result<Cow<'reg, str>, RenderError> {
        match self {
            Parameter::Name(ref name) => Ok(Cow::Borrowed(name)),
            Parameter::Path(ref p) => Ok(Cow::Borrowed(p.raw())),
            Parameter::Subexpression(_) => self
                .expand(registry, ctx, rc)
                .map(|v| v.value().render())
                .map(Cow::Owned),
            Parameter::Literal(ref j) => Ok(Cow::Owned(j.render())),
        }
    }

    pub fn expand<'reg: 'rc, 'rc>(
        &'reg self,
        registry: &'reg Registry<'reg>,
        ctx: &'rc Context,
        rc: &mut RenderContext<'reg, 'rc>,
    ) -> Result<PathAndJson<'reg, 'rc>, RenderError> {
        match self {
            Parameter::Name(ref name) => {
                // FIXME: raise error when expanding with name?
                Ok(PathAndJson::new(Some(name.to_owned()), ScopedJson::Missing))
            }
            Parameter::Path(ref path) => {
                if let Some(rc_context) = rc.context() {
                    let result = rc.evaluate2(rc_context.borrow(), path)?;
                    Ok(PathAndJson::new(
                        Some(path.raw().to_owned()),
                        ScopedJson::Derived(result.as_json().clone()),
                    ))
                } else {
                    let result = rc.evaluate2(ctx, path)?;
                    Ok(PathAndJson::new(Some(path.raw().to_owned()), result))
                }
            }
            Parameter::Literal(ref j) => Ok(PathAndJson::new(None, ScopedJson::Constant(j))),
            Parameter::Subexpression(ref t) => match *t.as_element() {
                Expression(ref ht) => {
                    let name = ht.name.expand_as_name(registry, ctx, rc)?;

                    let h = Helper::try_from_template(ht, registry, ctx, rc)?;
                    if let Some(ref d) = rc.get_local_helper(&name) {
                        call_helper_for_value(d.as_ref(), &h, registry, ctx, rc)
                    } else {
                        let mut helper = registry.get_or_load_helper(&name)?;

                        if helper.is_none() {
                            helper = registry.get_or_load_helper(if ht.block {
                                BLOCK_HELPER_MISSING
                            } else {
                                HELPER_MISSING
                            })?;
                        }

                        helper
                            .ok_or_else(|| {
                                RenderError::new(format!("Helper not defined: {:?}", ht.name))
                            })
                            .and_then(|d| call_helper_for_value(d.as_ref(), &h, registry, ctx, rc))
                    }
                }
                _ => unreachable!(),
            },
        }
    }
}

impl Renderable for Template {
    fn render<'reg: 'rc, 'rc>(
        &'reg self,
        registry: &'reg Registry<'reg>,
        ctx: &'rc Context,
        rc: &mut RenderContext<'reg, 'rc>,
        out: &mut dyn Output,
    ) -> Result<(), RenderError> {
        rc.set_current_template_name(self.name.as_ref());
        let iter = self.elements.iter();

        for (idx, t) in iter.enumerate() {
            t.render(registry, ctx, rc, out).map_err(|mut e| {
                // add line/col number if the template has mapping data
                if e.line_no.is_none() {
                    if let Some(&TemplateMapping(line, col)) = self.mapping.get(idx) {
                        e.line_no = Some(line);
                        e.column_no = Some(col);
                    }
                }

                if e.template_name.is_none() {
                    e.template_name = self.name.clone();
                }

                e
            })?;
        }
        Ok(())
    }
}

impl Evaluable for Template {
    fn eval<'reg: 'rc, 'rc>(
        &'reg self,
        registry: &'reg Registry<'reg>,
        ctx: &'rc Context,
        rc: &mut RenderContext<'reg, 'rc>,
    ) -> Result<(), RenderError> {
        let iter = self.elements.iter();

        for (idx, t) in iter.enumerate() {
            t.eval(registry, ctx, rc).map_err(|mut e| {
                if e.line_no.is_none() {
                    if let Some(&TemplateMapping(line, col)) = self.mapping.get(idx) {
                        e.line_no = Some(line);
                        e.column_no = Some(col);
                    }
                }

                e.template_name = self.name.clone();
                e
            })?;
        }
        Ok(())
    }
}

fn helper_exists<'reg: 'rc, 'rc>(
    name: &str,
    reg: &Registry<'reg>,
    rc: &RenderContext<'reg, 'rc>,
) -> bool {
    rc.has_local_helper(name) || reg.has_helper(name)
}

#[inline]
fn render_helper<'reg: 'rc, 'rc>(
    ht: &'reg HelperTemplate,
    registry: &'reg Registry<'reg>,
    ctx: &'rc Context,
    rc: &mut RenderContext<'reg, 'rc>,
    out: &mut dyn Output,
) -> Result<(), RenderError> {
    let h = Helper::try_from_template(ht, registry, ctx, rc)?;
    debug!(
        "Rendering helper: {:?}, params: {:?}, hash: {:?}",
        h.name(),
        h.params(),
        h.hash()
    );
    if let Some(ref d) = rc.get_local_helper(h.name()) {
        d.call(&h, registry, ctx, rc, out)
    } else {
        let mut helper = registry.get_or_load_helper(h.name())?;

        if helper.is_none() {
            helper = registry.get_or_load_helper(if ht.block {
                BLOCK_HELPER_MISSING
            } else {
                HELPER_MISSING
            })?;
        }

        helper
            .ok_or_else(|| RenderError::new(format!("Helper not defined: {:?}", h.name())))
            .and_then(|d| d.call(&h, registry, ctx, rc, out))
    }
}

pub(crate) fn do_escape(r: &Registry<'_>, rc: &RenderContext<'_, '_>, content: String) -> String {
    if !rc.is_disable_escape() {
        r.get_escape_fn()(&content)
    } else {
        content
    }
}

#[inline]
fn indent_aware_write(
    v: &str,
    rc: &mut RenderContext<'_, '_>,
    out: &mut dyn Output,
) -> Result<(), RenderError> {
    if let Some(indent) = rc.get_indent_string() {
        out.write(support::str::with_indent(v, indent).as_ref())?;
    } else {
        out.write(v.as_ref())?;
    }
    Ok(())
}

impl Renderable for TemplateElement {
    fn render<'reg: 'rc, 'rc>(
        &'reg self,
        registry: &'reg Registry<'reg>,
        ctx: &'rc Context,
        rc: &mut RenderContext<'reg, 'rc>,
        out: &mut dyn Output,
    ) -> Result<(), RenderError> {
        match self {
            RawString(ref v) => indent_aware_write(v.as_ref(), rc, out),
            Expression(ref ht) | HtmlExpression(ref ht) => {
                let is_html_expression = matches!(self, HtmlExpression(_));
                if is_html_expression {
                    rc.set_disable_escape(true);
                }

                // test if the expression is to render some value
                let result = if ht.is_name_only() {
                    let helper_name = ht.name.expand_as_name(registry, ctx, rc)?;
                    if helper_exists(&helper_name, registry, rc) {
                        render_helper(ht, registry, ctx, rc, out)
                    } else {
                        debug!("Rendering value: {:?}", ht.name);
                        let context_json = ht.name.expand(registry, ctx, rc)?;
                        if context_json.is_value_missing() {
                            if registry.strict_mode() {
                                Err(RenderError::strict_error(context_json.relative_path()))
                            } else {
                                // helper missing
                                if let Some(hook) = registry.get_or_load_helper(HELPER_MISSING)? {
                                    let h = Helper::try_from_template(ht, registry, ctx, rc)?;
                                    hook.call(&h, registry, ctx, rc, out)
                                } else {
                                    Ok(())
                                }
                            }
                        } else {
                            let rendered = context_json.value().render();
                            let output = do_escape(registry, rc, rendered);
                            indent_aware_write(output.as_ref(), rc, out)
                        }
                    }
                } else {
                    // this is a helper expression
                    render_helper(ht, registry, ctx, rc, out)
                };

                if is_html_expression {
                    rc.set_disable_escape(false);
                }

                result
            }
            HelperBlock(ref ht) => render_helper(ht, registry, ctx, rc, out),
            DecoratorExpression(_) | DecoratorBlock(_) => self.eval(registry, ctx, rc),
            PartialExpression(ref dt) | PartialBlock(ref dt) => {
                let di = Decorator::try_from_template(dt, registry, ctx, rc)?;

                partial::expand_partial(&di, registry, ctx, rc, out)
            }
            _ => Ok(()),
        }
    }

Implementors§

implement HelperDef for bare function so we can use function as helper