是否可以将把手表达式值传递给子表达式?

时间:2018-06-13 02:18:30

标签: javascript html handlebars.js jsreport

如果我的父上下文可以访问属性(索引),我可以将它传递给子表达式吗?我似乎无法让它发挥作用。我已经确认使用块传递给它的静态值(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}}

1 个答案:

答案 0 :(得分:0)

当您在子模板调用中使用动态数据时(如每次迭代中的索引),您必须小心,因为事情可能无法按预期工作。

例如使用类似的东西时

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

传递给实际子模板的内容是"parentIndex": "0 ",它可能并不明显,但是当您使用@data.parentIndex语法传递数据时,任何空间都很重要,因为您使用的是{#child child @data.parentIndex={{@index}} }最后一个空格(}),然后最终值包含该空格。

传递此方法的正确方法应该是{#child child @data.parentIndex={{@index}}},但这会引发一个把手错误,因为它会被子调用语法的括号弄糊涂。

工作方式是这样的:

父模板:

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

父模板的助手:

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

子模板:

{{parentIndex}}

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

这个工作的原因是因为我们避免把手被括号语法弄糊涂了,我们通过使用帮助器动态构造子调用来实现,最后在把手处理完模板后解析它。

最后here是此案例的实例

希望它可以帮到你。

相关问题