How to execute $ this-> render () inside symfony2 service?

I have this code inside a regular symfony2 controller:

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

And it works great.

Now I'm trying to port this to a service, but I don't know how to access the $ equivalent of this normal controller.

I tried to enter the container as follows:

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

But this did not work, and I assume that this is because the render does not actually use the $ this-> regular controller container, but only uses $ this part.

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

+6
source share
2 answers

Check the render method in the Symfony\Bundle\FrameworkBundle\Controller class. It says:

 return $this->container->get('templating')->render($view, $parameters); 

since you already have the container in your service, you can use it as in the above example.

NOTE. Including the entire container in the service is considered bad practice, in which case you should only enter the template engine and call the render method on the object template.

So the full 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) 
+15
source

Using constructor dependency injection (verified using 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'); } } 
+1
source

Source: https://habr.com/ru/post/969951/


All Articles