2017-01-16 66 views
0

product.html.twig:如何顯示在樹枝模板控制器陣列

<ul id="navigation">     
    <li> 
     <a href="<?php echo product.getId() ?>"> 
      <?php echo product.getDescription() ?> 
     </a> 
    </li> 
</ul> 

控制器的操作方法包括:

public function showAction($id = 5) 
{ 
    $product = $this->getDoctrine() 
     ->getRepository('AppBundle:Product') 
     ->find($id); 

    if (!$product) { 
     throw $this->createNotFoundException(
      'No product found for id '.$id 
     ); 
    } 
    else 
    { 
     return $this->render('default/productItem.html.twig', array(
      'id'=> $id, 
      'name' => $name)); 
    } 
} 

我不能在列表中看到

+0

難道是持有對象的數組? '$ product'是一個對象嗎? –

+1

爲什麼不用'href =「{{product.id}}」' – Matteo

回答

1

你輸出應該使用Twig語法。

<ul id="navigation">     
    <li> 
     <a href="/page.php?id={{ product.getId() }}"> 
      {{ product.getDescription() }} 
     </a> 
    </li> 
</ul> 

在你的情況下,你的輸入必須是一個對象。具有功能getId()getDescription()

在你的代碼可以去掉「get」和只寫例如{{ product.id }}

0

會建議一些更改控制器:

在你的控制器,你硬編碼您$id參數設置爲「5' 這可能是更好的使用路由註釋和有一個可選的參數,而不是使用defaults硬編碼任何。默認值。

此外,我建議您將其稱爲$productID,因此您知道它適用於產品實體,並將其與您在陣列中傳遞的內容(作爲參數)區分開來。

一LSO在你的示例代碼顯示您傳遞的idname的參數,但首先$name沒有在任何地方定義,$id是你在傳遞什麼作爲參數傳遞給控制器​​,但隨後在樹枝文件你不顯示使用根本沒有nameid!再加上你提供productItem.html.twig,但在帖子上方你可以稱之爲product.html.twig。那是不同的文件?

確保當您發佈問題,#2,一切都清楚了。

這裏是一個如何改變你的控制器代碼按我的建議上面的示例:

/** 
* @Route("/showproduct/{productID}", 
*  defaults={"productID" = 0}, 
*  name="showproduct 
*/ 
public function showAction($productID) 
{ 
    $product = $this->getDoctrine() 
     ->getRepository('AppBundle:Product') 
     ->find($productID); 

    if (!$product) { 
     throw $this->createNotFoundException(
      'No product found for id '.$productID 
     ); 
    } 
    else 
    { 
     return $this->render('default/productItem.html.twig', array(
      'product'=> $product, 
     )); 
    } 
} 

然後在你的樹枝文件(是productItem.html.twig ???)則是這樣的:

<ul id="navigation">     
    <li> 
     <a href="{{ product.getId }}"> 
      {{ product.getDescription }} 
     </a> 
    </li> 
</ul> 

希望它能幫助!