L.S L.S - 3 months ago 33
Twig Question

twig nested loop getting more elements

I have a nested loop in twig and i get the elements doubled in the form of 1,1,1,1 / 2,2,2,2 / 3,3,3,3. How can i use the first loop to access the data from the second loop without duplicating the elements ?

{% for form in forms %}
{% for question in surveyQuestions %}
<div class="overlay-container tab-content">
<div role="tabpanel" class="show-rendered-form tab-pane in fade active" id="show-rendered-form">
{% form_theme form with ['bootstrap_3_horizontal_layout.html.twig'] %}
{{ form(form) }}
<div class="overlay-mask">
<div class="btn-group">
<a class="edit-action btn btn-default" href="#show-edit-form"
data-question-id="{{ question.id }}" aria-controls="show-rendered-form"
role="tab" data-toggle="tab">Editeaza</a>
<a class="delete-action btn btn-default" href="#show-rendered-form"
data-question-id="{{ question.id }}" aria-controls="" role="tab"
data-toggle="tab">Sterge</a>
</div>
</div>
</div>
<div role="tabpanel" class="show-edit-form tab-pane" id="show-edit-form">

</div>
</div>
{% endfor %}
{% endfor %}

Answer

Assuming my assessment above is correct: Why not do it like this?

Instead of using a foreach loop, we use a classical for loop and use the index as identifier for both, forms and surveyQuestions:

{% for i in 0..(forms|length - 1)%}
        <div class="overlay-container tab-content">
            <div role="tabpanel" class="show-rendered-form tab-pane in fade active" id="show-rendered-form">
                {% form_theme form with ['bootstrap_3_horizontal_layout.html.twig'] %}
                {{ form(forms[i]) }}
                <div class="overlay-mask">
                    <div class="btn-group">
                        <a class="edit-action btn btn-default" href="#show-edit-form"
                           data-question-id="{{ surveyQuestions[i].id }}" aria-controls="show-rendered-form"
                           role="tab" data-toggle="tab">Editeaza</a>
                        <a class="delete-action btn btn-default" href="#show-rendered-form"
                           data-question-id="{{ surveyQuestions[i].id }}" aria-controls="" role="tab"
                           data-toggle="tab">Sterge</a>
                    </div>
                </div>
            </div>
            <div role="tabpanel" class="show-edit-form tab-pane" id="show-edit-form">

            </div>
        </div>
{% endfor %}
Comments