michaelmcgurk michaelmcgurk - 2 months ago 9
Twig Question

Index value in for loop with Twig

I'd like to store the iteration value to use in

data-target
so it would be
#question0
,
#quesion1
,
#question2
and so on...

I tried using
{{item.id}}
but this didn't work.

{% for item in post.get_field('qanda') %}
<div class="panel panel-default">
<div class="panel-heading accordion-toggle question-toggle collapsed"
data-parent="#faqAccordion" data-target="#question{{item.id}}"
data-toggle="collapse">
<h4 class="panel-title"><a class="ing">Q:
{{item.question}}</a></h4>
</div>
<div class="panel-collapse collapse" id="question{{item.id}}" style=
"height: 0px;">
<div class="panel-body">
{{item.answer}}
</div>
</div>{% endfor %}
</div>

Answer

You can use the variable loop.index0 (for zero based indexing).

data-target="#question{{loop.index0}}" 

should do what you want. See the for loop documentation for more info for more information.