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?
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');
}
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With