jonibegoode
jonibegoode

Reputation: 11

loop through key values of an array in twig

I have not been able to find my answer elsewhere (maybe because I didn't know how to ask google as I'm pretty new to this ;))

I'm working with symfony and twig.

I pass an array in my view with only one entry related to the id. It looks like this in my view

    array:2 [▼
  "sponsor" => Sponsor {#473 ▼
    -id: 5
    -sponsorCode: "FUT"
    -name: "MANULO"
    -city: "OLERDOLA"
    -zipCode: 0
    -address: ""
    -country: "ESPANA"
    -phoneNumber: 32767
    -email: ""
    -creationDate: DateTime {#470 ▶}
  }
  "app" => AppVariable {#476 ▶}
]

I know I can access each property by doing

{{sponsor.name}}

But I'm trying to do it through a loop for each field of this array

something like

{% for key, value in sponsor %}
   <div class="field-group">
     <div class="field">{{ key }}:</div>
     <div class="value">{{ value }}</div>
   </div>
{% endfor %}

Am I missing something?

Thank you very much

Upvotes: 0

Views: 5895

Answers (1)

PastyAndPeas
PastyAndPeas

Reputation: 108

From the TWIG documentation:

Keys Only

By default, a loop iterates over the values of the sequence. You can iterate on keys by using the keys filter:

<h1>Members</h1>
<ul>
    {% for key in users|keys %}
        <li>{{ key }}</li>
    {% endfor %}
</ul>

Keys and Values

You can also access both keys and values:

<h1>Members</h1> <ul>
    {% for key, user in users %}
        <li>{{ key }}: {{ user.username|e }}</li>
    {% endfor %} </ul>

https://twig.sensiolabs.org/doc/2.x/tags/for.html

Keep your eye on the TWIG documentation, its rather comprehensive.

Looking at your code, it looks ok. However, the issue could be that the {{value}} may need further identification, such as {{ value.id }}

Upvotes: 2

Related Questions