john_a john_a - 2 months ago 13
Twig Question

Iterating over key-value arrays in Twig?

I'm (finally) switching my site from Drupal7 to Symfony3.

I'm working on migrating my layout to .twig.

I've got a question about loops and key-value arrays.

I've configured a k/v array

{% set test = {
sec1: {
title: "title 1",
content: "content 1"
},
sec2: {
title: "title 2",
content: "content 2"
},
}
%}


I can reference any specific array element in other markup. E.g., this works as intended

<ul>
<li>
<h1>{{ test.sec1.title }}</h1>
<div>
<p>{{ test.sec1.content }}</p>
</div>
</li>
</ul>


Now I want to loop/repeat the block over a count of n. But trying this,

<ul>
{% for i in 1..5 %}
<li>
<h1>{{ test.sec{{ i }}.title }}</h1>
<div>
<p>{{ test.sec{{ i }}.content }}</p>
</div>
</li>
{% endfor %}
</ul>


fires an error

Unexpected token "punctuation" of value "{" ("end of print statement" expected) in default/index.html.twig at line 67.
500 Internal Server Error - Twig_Error_Syntax


I've been working with variations of these

http://twig.sensiolabs.org/doc/tags/for.html#iterating-over-keys


but can't get anything to work yet.

What's the right way to loop this list over the secN's in the key-value array?

Answer

The reason why your script does not work is that you cannot compose an object-property accessor like this.

What you probably need is iterating over a subset:

{% for sec in test|slice(0, 5) %}
    {{ sec.title }}
{% endfor %}

Or, if you do indeed need access to the key: iteration over key and value:

{% for key, sec in test %}
    {{ sec.title }}
    {{key}}
{% endfor %}

If you need to slice while still accessing the key, you could combine the latter with a check to the loop variables:

{% for key, sec in test %}
    {% if loop.index0 < 5 %}
        {{ sec.title }}
        {{key}}
    {% endif %}
{% endfor %}
Comments