0

I have a for-loop within another for-loop and I would like the inner for-loop to go through the array test[INDEX] with [INDEX] being the index of the outer for-loop. I know I can get the loops index with the variable {{ loop.index() }}, however I do not know how to apply that within the head of my inner loop.

I've tried {% for x in test.{{ loop.index0 }} %}, but that throws me the error

Expected name or number.

Is there any way to do this?

1 Answer 1

1

In twig you can also use the array notation to get values from a variable

A note here is that the default loop.index is 1 indexed so you might want to use loop.index0 to get the correct offset

{% for f in foo %}
    - {{ f }}: {{ bar[loop.index0] }}
{% endfor %}

As an alternative you can also get the key in the {% for key, value ... format

{% for key, value in foo %}
    - {{ value }}: {{ bar[key] }}
{% endfor %}

demo


edit

As for you comment, you can succesfuly use this in any inner-loop, here is a more readable example

{% for country in countries %}
    {{ country }}:
    {% if cities[loop.index0]|default %}
    <ul>
        {% for city in cities[loop.index0] %}
        <li>{{ city }}</li>
        {% endfor %}
    </ul>
    {% endif %}
{% endfor %}

demo

Sign up to request clarification or add additional context in comments.

5 Comments

I'm sorry, I don't fully understand how to apply this in the head of my loop. When I try {% for termin in test[loop.index0] %} it now throws me the error > Notice: Undefined index: loop
Why would you try to have that in the outer-loop?
I don't. As per my original question, I want the INNER-LOOP to go through test[INDEX OF OUTER-LOOP]
Still doesn't work. Like I mentioned in my last comment, {% for termin in test[loop.index0] %} throws me the error Notice: Undefined index: loop
Then please update your question with your current twig template, a dump of the data and expected output

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.