符号:显示所有字段和键(&A;T) [英] Symfony2 & Twig : display all fields and keys

查看:7
本文介绍了符号:显示所有字段和键(&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不是数组,因此什么都不会完成。

您需要做的是向模板传递一个带有$Attributes对象属性的数组。为此,您可以使用php get_Object_vars()函数。做一些类似的事情:

$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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆