迭代快递把手中的对象

问题描述 投票:0回答:1

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

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

循环内

<p>{{../userId}}</p>

工作正常,但在使用这个参数时

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

第二个参数是未定义的。

html node.js express handlebars.js
1个回答
1
投票

快速搜索后我发现了这个:

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

我总结一下,手把给出了一个选项,使用../语法来引用父范围。

例如:

<button onclick="loadStatistics({{seminarId}}, {{../userId}})">Do Something 1</button>


编辑:

随着进一步观察,我也发现了this answer类似的问题。显然,因为当你宣布一个#if时你在范围链中又上了一层,你需要考虑到这一点。

{{#if isRated}}
    <button onclick="loadStatistics({{seminarId}}, {{../../userId}})">Do Something 1</button>
{{else}}
    <button onclick="loadQuestionnaire({{seminarId}})">Do Something 2</button>
{{/if}}
© www.soinside.com 2019 - 2024. All rights reserved.