Symfony2和Twig:显示所有字段和键

use*_*729 6 entity symfony twig

我有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
    ));

}
Run Code Online (Sandbox Code Playgroud)

detail.html.twig:

    {% for key in attributes %} 
        <p>{{ value }} : {{ key }}</p>
    {% endfor %}
Run Code Online (Sandbox Code Playgroud)

key*_*her 9

不要仅仅满足于公共场所!获得私人/受保护!

public function detailAction($id){
    $em = $this->container->get('doctrine')->getEntityManager();

    $node = 'testEntity'
    $Attributes = $em->getRepository('TestBetaBundle:'.$node)->findOneById($id);

    // Must be a (FQCN) Fully Qualified ClassName !!!
    $MetaData = $em->getClassMetadata('Test\Beta\Bundle\Entity\'. $node);
    $fields = array();
    foreach ($MetaData->fieldNames as $value) {
        $fields[$value] = $Attributes->{'get'.ucfirst($value)}();
    }

    return $this->container
                ->get('templating')
                ->renderResponse('TestBetaBundle:test:detail.html.twig', 
                array(
                    'attributes' => $fields
                ));

}
Run Code Online (Sandbox Code Playgroud)


Car*_*dos 8

好.for在您的属性对象上使用Twig 循环无法完成您要做的事情.让我试着解释一下:
Twig for循环迭代对象的ARRAY,为数组中的每个对象运行循环内部.在您的情况下,$attributes不是一个数组,它是您通过findOneById调用重新获得的OBJECT .所以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
));
Run Code Online (Sandbox Code Playgroud)

在Twig模板中:

{% for key, value in properties %} 
    <p>{{ value }} : {{ key }}</p>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

考虑到这只会显示对象的公共属性.