我试图使用Twig来显示Doctrine 2实体对象的简单列表。对象是用DQL查询的未修改结果获取的。PHP代码是这样的:
/*
* I know the query in the Repository class works as I get the correct objects
* from the method and can iterate through them with foreach in PHP, displaying
* data from the object through getters, like ->getId()
*/
$received = $repo->getReceived($id);
/*
* This appears to work, the variables are assigned correctly.
*/
echo $template->render(array("received" => $received, "first" => $received[0]));
Twig模板包含:
{% for item in received %}
<li>Item: {{ item.id }}, {{ first.id }}</li>
{% endfor %}
奇怪的是,twig正确地迭代接收到的数组,数组中有三个对象,有三行输出,但id(或任何其他成员)在作为item访问时没有出来。Id但是第二个输出,第一个。Id,输出正确
我应该看到的是:
Item 1, 1
Item 2, 1
Item 3, 1
但是我看到的是:
Item , 1
Item , 1
Item , 1
我已经尝试了不同的变化来获得输出,但到目前为止没有任何工作,项目。item.getId getId () .
你知道我在这里错过了什么吗?
编辑转储输出
{{dump(received)}}返回以下内容:
array(3) {
[0]=>
object(Received)#219 (6) {
["id":"Received":private]=>
int(1)
... snip ...
}
[1]=>
object(Received)#208 (6) {
["id":"Received":private]=>
int(2)
... snip ...
}
[2]=>
object(Received)#210 (6) {
["id":"Received":private]=>
int(3)
... snip ...
我已经把它剪短了,这是三个完整的Doctrine实体对象,所以它们在数组中,看起来是正确的
我终于找到了一种方法,虽然我不明白为什么我需要这样做。我将数组更改为包含一组数组而不是对象,但这也不起作用。
然后,我用完全相同的结构创建了另一个数组进行测试,并且该数组没有任何问题。有人知道什么可能导致一个数组工作,而另一个失败吗?都是二维数组。最后我使用了二维数组并将小枝代码改为:
{% for item in received %}
<li>Item: {{ attribute(item, 'id') }}</li>
{% endfor %}
由于某种原因,这里需要attribute(),尽管我之前确实尝试过,但后来Twig抱怨attribute()不存在。