【问题标题】:Is it possible to pass in a handlebar expression value to a sub-expression?是否可以将车把表达式值传递给子表达式?
【发布时间】:2018-06-13 22:49:44
【问题描述】:

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

【问题讨论】:

    标签: javascript html handlebars.js jsreport


    【解决方案1】:

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

    例如当使用这样的东西时

    {{#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 是这个案例的一个活生生的例子

    希望对你有帮助。

    【讨论】:

    • 您先生真了不起。我不想因为我缺乏车把知识而打扰你们。我很欣赏这个* 100。我有一个与此类似的解决方案,但我一定有一个空间导致它无法工作。我在其他地方找不到的很好的解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    相关资源
    最近更新 更多