2012-08-02 95 views
6

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

} 

detail.html.twig:

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

回答

8

確定。你正在試圖做的事情不能用你的屬性對象上的Twig for循環來完成。讓我試着解釋一下:
Twig for循環遍歷對象的ARRAY,爲數組中的每個對象運行循環的內部。在你的情況下,$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 
)); 

而且在樹枝模板:

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

考慮到這隻會顯示你的對象的公共屬性。

+0

好點@卡洛斯 – Mick 2012-08-02 15:38:20

+0

謝謝!這是我的第一篇文章,我的英文不完美!它的工作原理... – user1571729 2012-08-02 15:48:36

-2

您應將其更改爲

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

它無法顯示。當我測試{{attributes.name}}或{{attributes.description}}時,一切正常。但在循環裏面什麼都沒有! – user1571729 2012-08-02 15:03:10

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

} 
+1

使用[PropertyAccess](http://symfony.com/doc/current/components/property_access/introduction.html)組件可能更合適。 – keyboardSmasher 2015-05-28 19:41:12

0

對於Symfony3

$em = $this->getDoctrine()->getEntityManager(); 

    $MetaData = $em->getClassMetadata('TestBetaBundle:Node'); 
    $fields = $MetaData->getFieldNames(); 

    return $this->render('test/detail.html.twig', array('fields'=>fields));