Search code examples
javascriptexpresshandlebars.jsexpress-handlebars

Handlebars access outer index in nested loop


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"


Solution

  • 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