Search code examples
javascripthtmlhandlebars.jsjsreport

Is it possible to pass in a handlebar expression value to a sub-expression?


If my parent context has access to a property (index), can I pass it into a subexpression? I can't seem to get it to work. I've confirmed that that with block works with a static value passed to it (1)

// Parent template
-----------------------------------------------------------------------------
{#child {{../report.ResourceName}}--{{Name}} @data.parentIndex={{@index}} }


// Child template
-----------------------------------------------------------------------------
{{parentIndex}} // displays correctly as 2

// does not render
{{#with (lookup report.sections parentIndex)}}
    Rendered: {{name}}
{{/with}}

// renders correctly
{{#with (lookup report.sections 2)}}
    Rendered: {{name}}
{{/with}}

Solution

  • when you use dynamic data in a child template call (like an index in a each iteration) you have to be careful because things may not work as your expect.

    for example when using something like this

    {{#each report.sections}} 
        {#child child @data.parentIndex={{@index}} }
        <br /> 
    {{/each}}
    

    what is passed to the actually child template is "parentIndex": "0 ", it may not be obvious but when you pass data using @data.parentIndex syntax any space matters and since you are using {#child child @data.parentIndex={{@index}} } that contains a space (}) in the end, then the final value contains that space.

    the correct way to pass this should be {#child child @data.parentIndex={{@index}}} but this throws a handlebars error because it gets confused by the brackets of the child call syntax.

    the way that works is like this:

    parent template:

    {{#each report.sections}} 
        {{{callChild @index}}}
        <br /> 
    {{/each}}
    

    helpers of parent template:

    function callChild(parentIndex) {
        return '{#child child @data.parentIndex=' + parentIndex + '}'
    }
    

    child template:

    {{parentIndex}}
    
    {{#with (lookup report.sections parentIndex)}}
        Rendered: {{name}}
    {{/with}}
    

    the reason this works is because we are avoiding handlebars getting confused by the brackets syntax, we do that by constructing the child call dynamically with a helper which in the end gets resolved after handlebars have processed the template.

    finally here is a live example of this case

    hope it helps you.