如何在symfony 2中将对象作为renderView()参数传递

1 php symfony

我有一个symfony 2的问题(我对这个框架很新,我想学习如何正确使用,所以我希望你能帮助我).

我的问题如下:

我想在模板中显示产品,我需要传递一些参数,如名称,描述和价格:

public function showAction($id)
{
    $product = $this->getDoctrine()->getRepository('AcmeReadBundle:Product')->find($id);
    if(!$product)
    {
        throw $this->createNotFoundException('error: not found');
    }
    $content = $this->renderView('AcmeReadBundle:Show:index.html.twig',$product);
    return new Response($content);
}
Run Code Online (Sandbox Code Playgroud)

如果我这样做,我有这个错误:

Catchable Fatal Error: Argument 2 passed to Symfony\Bundle\FrameworkBundle\Controller\Controller::renderView() must be of the type array, object given
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

Erf*_*fan 6

你做得很好,除了你应该将参数传递给数组中的模板,最好直接返回渲染模板!

public function showAction($id)
{
    $product = $this->getDoctrine()->getRepository('AcmeReadBundle:Product')->find($id);
    if(!$product)
    {
        throw $this->createNotFoundException('error: not found');
    }
    return $this->render('AcmeReadBundle:Show:index.html.twig', array('product'=> $product));
}
Run Code Online (Sandbox Code Playgroud)