首页 > 解决方案 > 是否可以将车把表达式值传递给子表达式?

问题描述

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

标签: javascripthtmlhandlebars.jsjsreport

解决方案


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

例如,当使用这样的东西时

{{#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}}

这样做的原因是因为我们避免把手被括号语法混淆,我们通过使用帮助器动态构造子调用来做到这一点,最终在把手处理模板后得到解决。

最后这里是这个案例的一个活生生的例子

希望它可以帮助你。


推荐阅读