符号:显示所有字段和键(&A;T) [英] Symfony2 & Twig : display all fields and keys
本文介绍了符号:显示所有字段和键(&A;T)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对symfony2和Twig有一个问题:我不知道如何显示动态加载的实体的所有字段。以下是我的代码(不显示任何内容!)
控制器:
public function detailAction($id)
{
$em = $this->container->get('doctrine')->getEntityManager();
$node = 'testEntity'
$Attributes = $em->getRepository('TestBetaBundle:'.$node)->findOneById($id);
return $this->container->get('templating')->renderResponse('TestBetaBundle:test:detail.html.twig',
array(
'attributes' => $Attributes
));
}
Detail.html.twig:
{% for key in attributes %}
<p>{{ value }} : {{ key }}</p>
{% endfor %}
推荐答案
正常。您尝试完成的操作不能通过Attributes对象上的Twigfor
循环来完成。让我试着解释一下:
Twigfor
循环遍历对象数组,为数组中的每个对象运行循环内部。在您的例子中,$attributes
不是数组,它是您通过findOneById
调用检索到的对象。因此,for
循环发现这不是一个数组,并且不运行循环内部,甚至一次也不运行,这就是您没有得到输出的原因。
@thecatontheFlat提出的解决方案也不起作用,因为它只是在数组上进行相同的迭代,只是您可以访问数组的键和值,但由于$attributes
不是数组,因此什么都不会完成。
$properties = get_object_vars ($Attributes);
return $this->container->get('templating')->renderResponse('TestBetaBundle:test:detail.html.twig',
array(
'attributes' => $Attributes
'properties' => $properties
));
和在Twig模板中:
{% for key, value in properties %}
<p>{{ value }} : {{ key }}</p>
{% endfor %}
请注意,这将仅显示您的对象的公共属性。
这篇关于符号:显示所有字段和键(&A;T)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文