0

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

3
  • Possible duplicate of Twig iterate over object properties Commented May 3, 2017 at 14:51
  • Any error message or incorrect result from you attempt? Please also read this how-to-ask to refine the question whenever needed. Commented May 3, 2017 at 15:15
  • No error message, It symply doesn't loop on what I want. I'm looking through the possible duplicate question but I'm really surprised this is not a feature of twig. Commented May 3, 2017 at 15:25

1 Answer 1

2

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

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

2 Comments

Thanks for your reply, I did read this part of the documentation but I think it is more related to if I had an array with multiple entries. This is not what I'm trying to do. In my case I want to loop on the values inside the array. As you see in the documentation inside their loop they are doing {{ user.username|e }}. I'm trying to loop for not having to write {{ user.username|e }} for each fields
OP is trying to loop object properties, which is not possible by the default for-loop in twig

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.