Twig遍历对象属性 [英] Twig iterate over object properties
问题描述
我在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 %}
我想知道stdClass类型的对象是否也有可能.
I was wondering whether this is possible for objects of type stdClass as well.
我希望Twig以属性名称作为键来迭代对象的属性值.而是完全不执行for循环中包含的指令块.
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.
推荐答案
您可以先将对象转换为数组.您可以构建自己的过滤器,将对象投射到数组.有关过滤器的更多信息,请参见: http://twig.sensiolabs.org/doc/advanced.html#filters
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
它可能看起来像这样:
{% for key, value in my_object|cast_to_array %}
这篇关于Twig遍历对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!