php Twig 迭代对象属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11841515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Twig iterate over object properties
提问by Bogdan
I read in the Twig documentation that it is possible to iterate over an associative array in the following manner:
我在 Twig 文档中读到,可以通过以下方式迭代关联数组:
{% for key, value in array %}
{{key}}
{{value}}
{% endfor %}
I was wondering whether this is possible for objects of type stdClass as well.
我想知道这是否也适用于 stdClass 类型的对象。
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.
我希望 Twig 以属性名称为键迭代对象的属性值。相反,for 循环中包含的指令块根本没有执行。
采纳答案by Tadeck
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
您可以先将对象转换为数组。您可以构建自己的过滤器,将您的对象投射到数组。有关过滤器的更多信息,请访问:http: //twig.sensiolabs.org/doc/advanced.html#filters
It could then look like that:
然后它看起来像这样:
{% for key, value in my_object|cast_to_array %}
回答by roberto.cr
After loading TWIG, add this filter:
加载 TWIG 后,添加此过滤器:
$twig->addFilter( new Twig_SimpleFilter('cast_to_array', function ($stdClassObject) {
$response = array();
foreach ($stdClassObject as $key => $value) {
$response[] = array($key, $value);
}
return $response;
}));
It's named cast_to_arrayafter Tadeck's suggestion. :) I'm sure it doesn't work for any kind of stdClass Object, but it sure solved my problem with printing PHP associative arrays:) Use it as follows:
它的命名cast_to_array后Tadeck的建议。:) 我确定它不适用于任何类型的stdClass Object,但它确实解决了我打印 PHP关联数组的问题:) 按如下方式使用它:
{% for key, value in my_object|cast_to_array %}
<td>{{ value.1 }}</td>
{% endfor %}
Side story
番外篇
Since I got into this SO page a lot, I think it's pertinent to show where I'm using Twig for iterating over object properties, so it's helpful for other people with the same problem: I was trying to print a table from a .json source, but PHP's json_decode transforms any "key" : "value"into a PHP associative array, which Twig doesn't print by default. So this filter cuts and delivers a regular array to be used by Twig.
因为我经常进入这个 SO 页面,所以我认为展示我在哪里使用 Twig 来迭代对象属性是相关的,所以它对其他有同样问题的人有帮助:我试图从 .json 打印表格源,但 PHP 的 json_decode 将任何"key" : "value"转换为 PHP 关联数组,默认情况下 Twig 不会打印。所以这个过滤器剪切并提供了一个规则数组,供 Twig 使用。
source.json
源文件
{
"user": {
"family": {
"table": [{
"First_Name": "John",
"Last_Name": "Foo",
"Age": 25,
"Role": "Brother"
}, {
"First_Name": "Mary",
"Last_Name": "Bar",
"Age": 14,
"Role": "Sister"
}, {
"First_Name": "Joe",
"Last_Name": "Baz",
"Age": 33,
"Role": "Uncle"
}]
}
}
}
Twig
枝条
<table>
<thead>
<tr> {# get table headers from the table row #}
{% for row in user.family.table.0|cast_to_array %}
<th>{{ row.0 | replace({'_': ' '}) }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for row in user.family.table %}
<tr>
{% for key, value in row|cast_to_array %}
<td>{{ value.1 }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
回答by Dung
To complete Tadeck's answer here is how:
要在此处完成 Tadeck 的回答,方法如下:
If you have not ever created or setup a Twig extension (filter), you will need to follow this instruction first http://symfony.com/doc/2.7/cookbook/templating/twig_extension.html
如果您从未创建或设置 Twig 扩展(过滤器),您需要先按照此说明进行操作http://symfony.com/doc/2.7/cookbook/templating/twig_extension.html
1) add to your AppBundle/Twig/AppExtension.php ('cast_to_array')
1) 添加到你的 AppBundle/Twig/AppExtension.php ('cast_to_array')
public function getFilters()
{
return array(
new \Twig_SimpleFilter('md2html', array($this, 'markdownToHtml'), array('is_safe' => array('html'))),
new \Twig_SimpleFilter('price', array($this, 'priceFilter')),
new \Twig_SimpleFilter('cast_to_array', array($this, 'objectFilter')),
);
}
2) add to your AppBundle/Twig/AppExtension.php
2) 添加到你的 AppBundle/Twig/AppExtension.php
public function objectFilter($stdClassObject) {
// Just typecast it to an array
$response = (array)$stdClassObject;
return $response;
}
3) In your example.html.twig loop thru with twig and the filter.
3) 在您的 example.html.twig 中,使用 twig 和过滤器循环。
{% for key, value in row|cast_to_array %}
<td id="col" class="hidden-xs">{{ value }}</td>
{% endfor %}
Done, I hope it helps. From Tadeck's pointer.
完成了,我希望它有帮助。来自 Tadeck 的指针。
回答by Guest9000000
I know this is old but, wouldn't
我知道这很旧,但不会
$assoc_array = json_decode(json_encode($stdClassObject), TRUE);
work just as well?
工作也一样?
回答by kbull
In case this helps someone else. You can have Twig iterate the properties of your object provided you implement PHP's Iterator interface.
万一这有助于其他人。只要实现了 PHP 的 Iterator 接口,就可以让 Twig 迭代对象的属性。
In my case I have a generic object the uses the magic methods __get(), __set(), __isset(), and __unset() while storing key value pairs in a private array. This works fine in Twig until you want to iterate over the object using something like this
就我而言,我有一个通用对象,它使用魔术方法 __get()、__set()、__isset() 和 __unset(),同时将键值对存储在私有数组中。这在 Twig 中工作正常,直到您想使用这样的东西迭代对象
<ul>
{% for prop, value in object %}
<li>{{prop|replace({'_': ' '})|title}}</li>
{% endfor %}
</ul>
To make it work I had to implement the Iterator interface. Then the above code worked perfectly.
为了使它工作,我必须实现 Iterator 接口。然后上面的代码完美运行。
Now because of the magic __get() the property names are not case sensitive either so each of these work also.
现在由于魔术 __get() 属性名称也不区分大小写,因此每个都可以使用。
<ul>
{% for object in arrayOfObjects %}
<li>{{ object.property }}</li>
<li>{{ object.Property }}</li>
<li>{{ object.PROPERTY }}</li>
{% endfor %}
</ul>

