如何在symfony2服务中执行$ this-> render()?

Mat*_*der 9 php symfony

我在正常的symfony2控制器中有这个代码:

            $temp = $this->render('BizTVArchiveBundle:ContentTemplate:'.$content[$i]['template'].'/view.html.twig', array(
                'c'=> $content[$i],
                'ordernumber' => 1,
            ));
Run Code Online (Sandbox Code Playgroud)

它工作正常.

现在我试图将其移动到服务,但我不知道如何访问相当于普通控制器的$ this.

我尝试像这样注入容器:

    $systemContainer = $this->container;

    $temp = $systemContainer->render('BizTVArchiveBundle:ContentTemplate:'.$content[$i]['template'].'/view.html.twig', array(
                'c'=> $content[$i],
                'ordernumber' => 1,
            ));
Run Code Online (Sandbox Code Playgroud)

但这不起作用,我猜这是因为渲染不是真正使用普通控制器的$ this->容器,而只使用$ this部分.

任何人都知道如何从服务中使用$ this-> render()?

Tom*_*ski 21

检查方法renderSymfony\Bundle\FrameworkBundle\Controller类.它说:

return $this->container->get('templating')->render($view, $parameters);
Run Code Online (Sandbox Code Playgroud)

因此,由于您的服务中已有容器,您可以像上面的示例一样使用它.

注意:将整个容器注入服务被认为是不好的做法,在这种情况下你应该只注入模板引擎并render在模板对象上调用方法.

如此完整的图片:

services.yml:

services:
    your_service_name:
        class: Acme\YourSeviceClass
        arguments: [@templating]
Run Code Online (Sandbox Code Playgroud)

你的班:

public function __construct($templating)
{ 
    $this->templating = $templating
}
Run Code Online (Sandbox Code Playgroud)

和你的渲染电话:

$this->templating->render($view, $parameters)
Run Code Online (Sandbox Code Playgroud)


Mat*_*usz 5

使用构造函数依赖注入(用 Symfony 3.4 测试):

class MyService
{
    private $templating;

    public function __construct(\Twig_Environment $templating)
    {
        $this->templating = $templating;
    }

    public function foo()
    {
        return $this->templating->render('bar/foo.html.twig');
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 在我的 Symfony 2.8 应用程序中,我注入了一个 Symfony\Bundle\TwigBundle\TwigEngine 实例而不是 \Twig_Environment。 (3认同)