express - 在子表达式中传递“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
上面定义的类别数组上的当前迭代进行比较,我该怎么做?
解决方案
您确实需要指定上面的代码不起作用的地方。
事实上,它对我来说看起来不错,除了两件事:
- 当您在上下文中时,
#each
没有product
要在其上查找的对象category
,因此您将需要使用指向更高评估上下文的路径,例如../product.category
. - 无需将
this
调用optionSelected
括在括号中。事实上,在我的测试中,括号似乎导致了编译器错误。
以下是一个完全有效的模板:
{{#each categories}}
<option value="{{this}}" {{optionSelected ../product.category this}}>{{this}}</option>
{{/each}}
这是一个供参考的小提琴。
推荐阅读
- java - setBounds(x,y,width,height) 和 setBounds(new Rectangle(x,y,width,height)) 的区别
- xml - XSLT Date range to each day
- c++ - 根据 jpeglib.h 编译 c++ 程序
- java - Get Gremlin query as a String and execute it in java without submitting it to the GremlinServer
- mysql - 通过特定分隔符缩短特定字段内容
- android - Adview Error!- Incompatible types: View cannot be converted to Adview
- typescript - Error in typescript: property .ref does not exist on type 'AngularFireStorageModule'
- electron - Program white-screening all of a sudden
- javascript - 如何使 Wikipedia API 与 Fetch 一起使用?
- java - Android Studio: What does this Error mean?