2

Say I have the following code:

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

How can I access the outer loop's index (question index) inside of the inner (answer) loop? Essentially I want the id in the format of "answer_questionIndex_answerIndex"

Markus Meskanen
  • 19,939
  • 18
  • 80
  • 119
  • I was gonna say: start with [this link](https://stackoverflow.com/questions/11884960/how-to-get-index-in-handlebars-each-helper) to learn how to get index or key as required, and then combine that with [this link](https://stackoverflow.com/questions/45241022/assign-a-variable-in-handlebars) – TKoL Dec 19 '19 at 14:40
  • However, I no longer think that's possible, and you might have to do some data manipulation BEFORE you render your data -- put the index of the quesion inside the answers or the question, as a property – TKoL Dec 19 '19 at 14:40

1 Answers1

4

Found this deep in some documentation

Block Parameters

New in Handlebars 3.0, it's possible to receive named parameters from supporting helpers.

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

In this particular example, user will have the same value as the current context and userId will have the index value for the iteration.

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

Community
  • 1
  • 1
TKoL
  • 13,158
  • 3
  • 39
  • 73
  • 1
    I spent way too much time browsing the documentations and googling and found nothing, but this is perfect! Thank you very much – Markus Meskanen Dec 19 '19 at 14:56