unknown
unknown

Reputation: 45

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?

Upvotes: 1

Views: 2877

Answers (2)

Pradeep
Pradeep

Reputation: 317

       {% for key, item in content.field_invoice_no if key|first != '#' %} 
<tr>
       <td>{{ item }}</td>
       <td> {{ content.field_invoice_date[key] }}      </td>
</tr>
        {% endfor %}

Iterating over key-value arrays in Twig

for reference entity code below

 {% for  key, item1 in node.field_quotation.entity.field_product  %} 
     <tr>
        <td>{{ loop.index }}</td>
        <td>{{ item1.entity.body.value |raw }}</td>
         <td> {{ item1.entity.field_product_unit_required.value }}</td>
         <td>{{ item1.entity.field_hsn_code.value }}</td>
        <td>{{item1.entity.field_pro.number|number_format(2, '.', ',')}}</td>
 {% endfor %}        
      </tr>

Upvotes: 0

Jojo
Jojo

Reputation: 2760

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 %}

Upvotes: 2

Related Questions