簡體   English   中英

如何在樹枝模板中顯示控制器陣列

[英]How to display a Controller array in twig template

product.html.twig:

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

Controller Action方法包含:

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

我在列表中看不到輸出

您應該使用Twig語法。

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

在您的情況下,您的輸入必須是一個對象。 使用功能getId()getDescription()

例如,在您的代碼中,您可以刪除“ get”並僅編寫{{ product.id }}

建議您對控制器進行一些更改:

在您的控制器中,您將$id參數硬編碼為“ 5”。最好使用路由注釋並使用一個可選參數。使用defaults對任何默認值進行硬編碼。

另外,我建議您將其命名為$productID ,而不是$id ,這樣您就知道它是用於Product Entity的,並與將數組(作為參數)傳遞給twig控制器的內容區分開來。

同樣在示例代碼中,您還顯示了傳入idname的參數,但是首先$name沒有在任何地方定義,而$id是您作為參數傳遞給Controller的內容,但是在您的twig文件中卻沒有顯示完全使用nameid 另外,您可以渲染productItem.html.twig ,但是在帖子上方,您將其稱為product.html.twig 那是一個不同的文件嗎?

確保在Stackoverflow上發布問題時一切都清楚。

這是按照上面我的建議如何更改控制器代碼的示例:

/**
 * @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>

希望能幫助到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM