K. Pradnyana
K. Pradnyana

Reputation: 77

Get value with Twig for loop from array

I have an array like this

'contents' => array(
              'row' => array(
                    'col-xs-6' => 'grid 1',
                    'col-xs-6' => 'grid 2'
              ),
              'row' => array(
                    'col-xs-6' => 'grid 3',
                    'col-xs-6' => 'grid 4'
              )
        )

Now I want to get the key from the array but failed, I have try with this code

{% for key, values in contents %}
     <div class="{{ key }}">
          {% for klass, contain in values %}
                 <div class="{{ klass }}">
                      {{ contain }}
                 </div>
          {% endfor %}
     </div>
{% endfor %}

Output:

<div class="row"><div class="col-xs-6">grid 4</div></div>

I don't know why it only appear once, but if I try changing the key name with different value and it works. Please help me. Thank you.

Upvotes: 0

Views: 126

Answers (2)

Alvin Bunk
Alvin Bunk

Reputation: 7764

Based on your comments:

So let's say you pass in a variable called gridCount, then in Twig you can code like so:

{% for i in 0..gridCount %}
    <div class="row"><div class="col-xs-6">grid {{ i }}</div></div>
{% endfor %}

Let me know if you also plan to change the class values. In the above, I presume you don't need to. But if they are also dynamic, then you need to tell me how they change.

Upvotes: 1

Thamilhan
Thamilhan

Reputation: 13303

PHP array should have unique keys.

In your case,

  1. First row gets replaced by second row
  2. First col-xs-6 in the second row will be replaced by second col-xs-6

So, your resultant array would be:

'contents' => array(
      'row' => array(
            'col-xs-6' => 'grid 4'
      )
)

Upvotes: 4

Related Questions