如何在树枝模板中显示Controller数组

时间:2017-01-16 17:02:39

标签: php symfony twig

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

我无法看到列表中的输出

2 个答案:

答案 0 :(得分:1)

您应该使用Twig语法。

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

在您的情况下,您的输入必须是一个对象。功能getId()getDescription()

在您的代码中,您可以删除&#34; get&#34;并且只写{{ product.id }}例如。

答案 1 :(得分:0)

建议您对控制器进行一些更改:

在您的控制器中,您将$id参数硬编码为&#34; 5&#39;。使用路由注释可能更好,而是使用可选参数。使用defaults对任何默认值进行硬编码。

此外,我建议您将其称为$id,而不是$productID,因此您知道它是针对产品实体的,并将其与您在数组中传递的内容(作为参数)区分开来到你的枝条控制器。

同样在您的示例代码中,您显示了传递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,
        ));
    }
}

然后在你的twig文件中(是​​productItem.html.twig ???)然后像这样:

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

希望它有所帮助!

相关问题