Search code examples
htmlhandlebars.jsassemblegrunt-assemble

Assemble (templates): Get parent value from within nested each block


I have a problem getting a value from a parent loop/each. How can I do this?

I'm looping through some questions, and then loop through some answers. On each answer I would like to add the question ID..

The JSON:

{
    "questions": [
        {
            "id": 1,
            "answers": [
                ...
                ...
                ...
            ]
        }
    ]

}

And the Assemble.io nested loops/each

{{#forEach questions}}
    <h2>{{id}}</h2>
    <ul>
        {{#forEach this.answers}}
            <li>
                <input type="radio" name="{{id}}" id="{{id}}-{{index}}"/>
            </li>
        {{/forEach}}
    </ul>
{{/forEach}}

Do you know how I can get the ID from the parent loop/each?

Thank you in advance... :-)


Solution

  • In handlebars, you can use the parent accessor syntax ../

    {{#forEach questions}}
        <h2>{{id}}</h2>
        <ul>
            {{#forEach this.answers}}
                <li>
                    <input type="radio" name="{{../id}}" id="{{../id}}-{{index}}"/>
                </li>
            {{/forEach}}
        </ul>
    {{/forEach}}