Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to perform $this->render() inside symfony2 service?

Tags:

php

symfony

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

And it works fine.

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

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.

Anyone know how to use $this->render() from a service?

like image 373
Matt Welander Avatar asked May 28 '14 10:05

Matt Welander


2 Answers

Using constructor dependency injection (tested with 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');
    }
}
like image 57
Mateusz Avatar answered Nov 17 '22 08:11

Mateusz


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.

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.

So complete picture:

services.yml:

services:
    your_service_name:
        class: Acme\YourSeviceClass
        arguments: [@templating]

your class:

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

and your render call:

$this->templating->render($view, $parameters)
like image 22
Tomasz Madeyski Avatar answered Nov 17 '22 07:11

Tomasz Madeyski