Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig iterate over object properties

Tags:

php

twig

I read in the Twig documentation that it is possible to iterate over an associative array in the following manner:

{% for key, value in array %}    {{key}}    {{value}}   {% endfor %}   

I was wondering whether this is possible for objects of type stdClass as well.

I would have expected Twig to iterate over the property values of the object taking the property names as keys. Instead, the instruction block contained in the for loop is not executed at all.

like image 432
Bogdan Avatar asked Aug 07 '12 07:08

Bogdan


1 Answers

You can first cast the object to array. You can build own filter casting your object to array. More about filters is available here: http://twig.sensiolabs.org/doc/advanced.html#filters

It could then look like that:

{% for key, value in my_object|cast_to_array %} 
like image 50
Tadeck Avatar answered Oct 17 '22 17:10

Tadeck