【问题标题】:Passing 'this' inside a subexpression在子表达式中传递“this”
【发布时间】: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


【解决方案1】:

您确实需要指定 什么 对上面的代码不起作用。

事实上,我觉得它看起来不错,除了两点:

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

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

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

这是一个fiddle 供参考。

【讨论】:

  • 您的解决方案有效。我想弄清楚它为什么起作用。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-21
  • 1970-01-01
相关资源
最近更新 更多