【问题标题】:Handlebars access outer index in nested loop把手在嵌套循环中访问外部索引
【发布时间】:2020-04-12 03:58:09
【问题描述】:

假设我有以下代码:

<div>
  {{#each questions}}
  <div id="question_{{@index}}">
    {{#each this.answers}}
    <div id="answer_{{???}}_{{@index}}">
      {{this}}
    </div>
    {{/each}}
  </div>
  {{/each}
</div>

如何在内部(答案)循环中访问外部循环的索引(问题索引)?基本上我想要id 格式为"answer_questionIndex_answerIndex"

【问题讨论】:

  • 我想说:从this link开始学习如何根据需要获取索引或键,然后将其与this link结合起来
  • 但是,我不再认为这是可能的,您可能必须在呈现数据之前进行一些数据操作——将问题的索引作为属性放在答案或问题中

标签: javascript express handlebars.js express-handlebars


【解决方案1】:

在一些文档中发现了这一点

块参数

Handlebars 3.0 中的新功能,可以从支持助手接收命名参数。

{{#each users as |user userId|}}
  Id: {{userId}} Name: {{user.name}}
{{/each}}

在这个特定示例中,user 将具有与当前上下文相同的值,而 userId 将具有迭代的索引值。

https://handlebarsjs.com/guide/block-helpers.html#hash-arguments

【讨论】:

  • 我花了太多时间浏览文档和谷歌搜索却一无所获,但这是完美的!非常感谢
猜你喜欢
  • 2018-02-10
  • 1970-01-01
  • 2021-03-06
  • 2016-05-24
  • 2021-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多