如何在 symfony2 服务中执行 $this->render() ? [英] how to perform $this->render() inside symfony2 service?
问题描述
我在一个普通的 symfony2 控制器中有这个代码:
I have this code inside a normal symfony2 controller:
$temp = $this->render('BizTVArchiveBundle:ContentTemplate:'.$content[$i]['template'].'/view.html.twig', array(
'c'=> $content[$i],
'ordernumber' => 1,
));
而且效果很好.
现在我正在尝试将其移至服务,但我不知道如何访问普通控制器的 $this 等效项.
Now I am trying to move this to a service, but I don't know how to access the equivalent of $this of the normal controller.
我尝试像这样注入容器:
I tried injecting the container like this:
$systemContainer = $this->container;
$temp = $systemContainer->render('BizTVArchiveBundle:ContentTemplate:'.$content[$i]['template'].'/view.html.twig', array(
'c'=> $content[$i],
'ordernumber' => 1,
));
但是那没有用,我想那是因为 render 并没有真正使用普通控制器的 $this-> 容器,而只是使用了 $this 部分.
But that didn't work, and I guess that is because render isn't really using the $this->container of the normal controller but only using the $this part.
有人知道如何从服务中使用 $this->render() 吗?
Anyone know how to use $this->render() from a service?
推荐答案
检查Symfony\Bundle\FrameworkBundle\Controller
类中的render
方法.它说:
Check method render
in Symfony\Bundle\FrameworkBundle\Controller
class. It says:
return $this->container->get('templating')->render($view, $parameters);
因此,由于您的服务中已经有容器,因此您可以像上面的示例一样使用它.
so since you have container already in your service you can use it like in above example.
注意:将整个容器注入服务被认为是不好的做法,在这种情况下,您应该只注入模板引擎,并在模板对象上调用 render
方法.
NOTE: injecting whole container into service is considered as bad practice, you should inject only templating engine in this case and call render
method on templating object.
如此完整的图片:
services.yml
:
services:
your_service_name:
class: Acme\YourSeviceClass
arguments: [@templating]
你的班级:
public function __construct($templating)
{
$this->templating = $templating
}
和您的渲染调用:
$this->templating->render($view, $parameters)
这篇关于如何在 symfony2 服务中执行 $this->render() ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!