简体   繁体   English

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

[英]how to pass an object as renderView() parameter in symfony 2

I have a problem with symfony 2 ( I'm pretty new with this framework and I would like to learn how to use correctly so I hope you can help me). 我对symfony 2有问题(我对这个框架还很陌生,我想学习如何正确使用它,希望对我有所帮助)。

My problem is the following: 我的问题如下:

I want to show a product in a template and I need to pass some parameters like name, description and price about him: 我想在模板中显示产品,我需要传递一些有关他的名称,描述和价格之类的参数:

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

If I do this I have this error: 如果执行此操作,则会出现此错误:

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

How can I fix this? 我怎样才能解决这个问题?

you did quite alright, except you should pass parameters to templates in an array and it is better to return rendered template directly! 您做得还不错,只不过您应该将参数传递给数组中的模板,最好直接返回渲染的模板!

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

you need to put: 您需要输入:

$return $this->renderView('AcmeReadBundle:Show:index.html.twig',array('product' => $product));

you shoud pass parameters like array 你应该传递像数组这样的参数

If template AcmeReadBundle:Show:index.html.twig is made for Product , it is wrong to put another "product" prefix in front of expressions, like so: 如果为Product制作了模板AcmeReadBundle:Show:index.html.twig ,则在表达式之前放置另一个“ product”前缀是错误的,如下所示:

{{ product.title }}
{{ product.price }}

It is right to look it like this: 看起来像这样是正确的

{{ title }}
{{ price }}

in template. 在模板中。 So wrapping is a bad option. 因此,包装是一个不好的选择。 Best option is to use get_object_vars() , it automatically converts object to an array: 最好的选择是使用get_object_vars() ,它会自动将对象转换为数组:

return $this->render('AcmeReadBundle:Show:index.html.twig', get_object_vars($product));        

This way you can use this template calling it from another template (because it doesn't contain "product"-prefix before every expression), when iterating thru Products collection for example, because your Products collection would contain collection of Products , not collection of Arrays of 1 object which is Product . 这样,您就可以使用这个模板调用它从另一个模板(因为它不包含每一个表情之前的“产品” -前缀),迭代时通Products集合例如,因为你的Products集合将包含集合Products ,而不是收集Arrays of 1 object which is Product

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM