【发布时间】:2021-10-08 09:57:32
【问题描述】:
目前,我正在使用 #each 帮助器来循环数组。该数组用于传递信息,使用我的文档创建列表项
const categories = ['fruit', 'vegetables', 'dairy']
{{#each categories}}
<option value="{{this}}" {{optionSelected product.category (this) }}>{{this}}</option>
{{/each}}
我正在使用 optionSelected 自定义助手来切换选项上的选定属性
hbs.handlebars.registerHelper('optionSelected', function (test, option) {
return test === option ? 'selected' : '';
})
编写的代码不起作用。如果想将product.category 与上面定义的类别数组上的当前迭代进行比较,我该怎么做?
【问题讨论】:
-
我认为您需要增加一两个评估上下文才能访问您的
product对象。确切的路径将取决于数据的形状,但它看起来类似于../product.category。 -
我可以在我所在的上下文中很好地访问产品对象。我的问题是,在我的每个块中,我试图将每个当前迭代作为参数传递给我的自定义帮助函数。我不能将关键字“this”作为参数传递吗?
-
您可以绝对将
this传递给助手。请参阅下面的答案。
标签: express handlebars.js templating