【问题标题】:iterating over objects in express-handlebars迭代快速车把中的对象
【发布时间】:2018-06-07 13:10:09
【问题描述】:

这是我传递给车把模板的模型

module.exports = function(showHeader, userId){ // the data model
  return {
    userId: userId,
    seminars: userSeminars;
  };
};

var userSeminars = [{ // some information
    seminarId: 1,
    isRated: true
}, {
    seminarId: 2,
    isRated: false
}];

在渲染我的模板时,我使用这个 HTML 代码

{{#each seminars}}
    <div class="seminarContainer">

        {{#if isRated}}
            <button onclick="loadStatistics({{seminarId}}, {{userId}})">Do Something 1</button>
        {{else}}
            <button onclick="loadQuestionnaire({{seminarId}})">Do Something 2</button>
        {{/if}}
    </div>
{{/each}}

但在调试时,{{userId}} 未定义。我去了这个测试例程并将它写在上面每个循环

$(document).ready(function () {
   alert({{userId}}); // this works
});

userId 不是未定义的。但是当迭代数组时它是未定义的。如何将数组范围留在循环中?我必须访问数据模型对象,而不是数组中的属性。


编辑

Access a variable outside the scope of a Handlebars.js each loop

当我想离开范围时,我可以使用{{../userId}}

循环内

&lt;p&gt;{{../userId}}&lt;/p&gt;

工作正常,但将其用于

等参数时

onclick="loadStatistics({{seminarId}}, {{../userId}})"

第二个参数未定义。

【问题讨论】:

    标签: html node.js express handlebars.js


    【解决方案1】:

    经过快速搜索,我发现了这个:

    Access a variable outside the scope of a Handlebars.js each loop

    我总结一下,handlebars 提供了一个选项来使用../ 语法来引用父作用域

    例如:

    &lt;button onclick="loadStatistics({{seminarId}}, {{../userId}})"&gt;Do Something 1&lt;/button&gt;


    编辑:

    进一步看,我还发现this answer 有一个类似的问题。显然,因为当您声明 #if 时,您在作用域链中又上了一层楼,因此您也需要考虑到这一点。

    {{#if isRated}}
        <button onclick="loadStatistics({{seminarId}}, {{../../userId}})">Do Something 1</button>
    {{else}}
        <button onclick="loadQuestionnaire({{seminarId}})">Do Something 2</button>
    {{/if}}
    

    【讨论】:

    • hm 是的,这是一个好的开始,但是当传入参数 onclick="loadStatistics({{seminarId}}, {{../userId}})" 时,它仍然是未定义的。当写 &lt;p&gt;{{../userId}}&lt;/p&gt; 时它可以工作
    • 我编辑了我的答案,请尝试一下,让我知道结果如何。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 2020-01-16
    • 2014-12-19
    相关资源
    最近更新 更多