2015-04-16 57 views
2

我正在學習symfony2,並且第一次我真的陷入了困境,不知道該怎麼做。我創建了3個頁面,索引頁面,產品頁面和特別優惠頁面。所有這些頁面都需要使用另一個模板中的一個動態邊欄。Symfony2包括帶控制器變量的樹枝

下面是操作,所述控制器:

public function indexAction() ///// im showing the products form mysql here 
    { 

      $em = $this->getDoctrine()->getManager(); 
      $products = $em->getRepository('MpShopBundle:Product')->findAll(); 
       return $this->render('MpShopBundle:Frontend:index.html.twig', array(
       'products'=>$products  
       )); 

    } 
    public function viewAction($id) //// im showing a single product based on the id 
    { 

     $em = $this->getDoctrine()->getManager(); 
     $product = $em->getRepository('MpShopBundle:Product')->find($id); 

     return $this->render('MpShopBundle:Frontend:product_details.html.twig', array(
     'product'=>$product 
     )); 

    } 

    public function specialAction() //// a simple page to test the sidebar 
    { 

      $em = $this->getDoctrine()->getManager(); 
      $products = $em->getRepository('MpShopBundle:Product')->findAll(); 
       return $this->render('MpShopBundle:Frontend:special_offer.html.twig', array(
       'products'=>$products  
       )); 

    } 

這是邊欄的模板代碼,用於生成的類別(類別中僅示出如果產品有它):

{% for product in products %} 

       <li class="subMenu"><a> {{ product.category }} [{{ product|length }}]</a> 
       <ul> 
        <li><a href="{{ path('products') }}">{{ product.subcategory }} ({{ product|length }})</a></li> 

       </ul> 
       </li> 

      {% endfor %} 

我包括我的頁面上的側邊欄模板,如下所示:

{% block sidebar %} {% include 'sidebar.html.twig' %} {% endblock %}

問題:它在索引和特價商品頁面上完美工作,但在視圖頁上我得到未定義的變量產品錯誤。我想我知道這個問題,因爲我在控制器中的那個頁面的變量是產品(獲得特定產品)。那麼,我如何才能使這個側邊欄在所有網頁上都能正常工作?

FIXED該問題已通過使用http://symfony.com/doc/2.0/book/templating.html#embedding-controllers教程得到修復。如果有人有相同的問題,請閱讀!

+0

您需要傳遞此產品$ products = $ em-> getRepository('MpShopBundle:Product') - > findAll();在返回語句, 返回$這 - >渲染( 'MpShopBundle:前端:product_details.html.twig',陣列( '產物'=> $產物, '產品'=> $產品 )); – herr

+0

這不起作用,因爲現在我得到一個未定義的變量產品。 – Dominykas55

+0

在哪一點? – Jean

回答

0
public function viewAction($id) //// im showing a single product based on the id 
{ 

    $em = $this->getDoctrine()->getManager(); 
    $product = $em->getRepository('MpShopBundle:Product')->find($id); 
    $products = $em->getRepository('MpShopBundle:Product')->findAll(); 

    return $this->render('MpShopBundle:Frontend:product_details.html.twig', array(
     'product' => $product, 
     'products' => $products 
    )); 

} 
+0

我用embedd控制器修復了它,但是我嘗試了你的代碼,它也起作用了。謝謝!!!! – Dominykas55