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

查看:63
本文介绍了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 循环遍历对象的数组,为循环中的每个对象运行循环内部数组。在您的情况下, $ attribute 不是数组,而是一个对象,您可以通过 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模板中:

{% 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和Twig:显示所有字段和键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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