首页 > 解决方案 > 在子表达式中传递“this”

问题描述

目前,我正在使用 #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上面定义的类别数组上的当前迭代进行比较,我该怎么做?

标签: expresshandlebars.jstemplating

解决方案


确实需要指定上面的代码不起作用的地方。

事实上,它对我来说看起来不错,除了两件事:

  1. 当您在上下文中时,#each没有product要在其上查找的对象category,因此您将需要使用指向更高评估上下文的路径,例如../product.category.
  2. 无需将this调用optionSelected括在括号中。事实上,在我的测试中,括号似乎导致了编译器错误。

以下是一个完全有效的模板:

{{#each categories}}
    <option value="{{this}}" {{optionSelected ../product.category this}}>{{this}}</option>
{{/each}}

这是一个供参考的小提琴。


推荐阅读