Symfony2 &Twig :显示所有字段和键 [英] Symfony2 & Twig : display all fields and keys

查看:23
本文介绍了Symfony2 &Twig :显示所有字段和键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Symfony2 和 Twig 有疑问:我不知道如何显示动态加载的实体的所有字段.这是我的代码(什么都不显示!!)

I have a problem with Symfony2 and Twig: I don't know how to display all fields of my entity which is loaded dynamically. Here is my code (displays nothing!!)

控制器:

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:

detail.html.twig :

    {% for key in attributes %} 
        <p>{{ value }} : {{ key }}</p>
    {% endfor %}

推荐答案

好的.你试图做的事情不能用 Twig for 循环在你的属性对象上完成.让我试着解释一下:
Twig for 循环遍历对象数组,为数组中的每个对象运行循环内部.在您的情况下, $attributes 不是数组,它是您通过 findOneById 调用检索的对象.所以 for 循环发现这不是一个数组,并且没有在循环内部运行,甚至一次都没有,这就是你没有输出的原因.@thecatontheflat 提出的解决方案也不起作用,因为它只是对数组的相同迭代,只是您可以访问数组的键和值,但由于 $attributes 不是一个数组,什么都做不了.

OK. What you are trying to do cannot be done with a Twig for loop over your attributes object. Let me try to explain:
The Twig for loop iterates over an ARRAY of objects, running the inside of the loop for each of the objects in the array. In your case, $attributes is NOT an array, it is an OBJECT which you retrived with your findOneById call. So the for loop finds that this is not an array and does not run the inside of the loop, not even once, that is why you get no output.
The solution proposed by @thecatontheflat does not work either, as it is just the same iteration over an array, only that you have access to both the keys and values of the array, but since $attributes is not an array, nothing is accomplished.

您需要做的是向模板传递一个包含 $Attributes 对象属性的数组.您可以为此使用 php get_object_vars() 函数.执行以下操作:

What you need to do is pass the template an array with the properties of the $Attributes object. You can use the php get_object_vars() function for this. Do something like:

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

在 Twig 模板中:

And in the Twig template:

{% for key, value in properties %} 
    <p>{{ value }} : {{ key }}</p>
{% endfor %}

请注意,这只会显示您对象的公共属性.

Take into account that this will only show the public properties of your object.

这篇关于Symfony2 &amp;Twig :显示所有字段和键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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