Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
603 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...