3
votes

I have custom Service and I would like to use it in Twig templates. In Symfony < 3 I can do:

use Symfony\Component\DependencyInjection\Container;
//...
public function __construct(Container $container) 
{
    $this->container = $container;
}

public function getView()
{
    $this->container->get('templating')->render('default/view.html.twig');
}

But in Symfony 3.3 I have error:

Cannot autowire service "AppBundle\Service\ViewService": argument "$container" of method "__construct()" references class "Symfony\Component\DependencyInjection\Container" but no such service exists. Try changing the type-hint to one of its parents: interface "Psr\Container\ContainerInterface", or interface "Symfony\Component\DependencyInjection\ContainerInterface".

1

1 Answers

0
votes

It's not good idea to inject whole container. Better is to inject single dependencies:

use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;

class MyService
{
    private $templating;
    public function __construct(EngineInterface $templating)
    {
        $this->templating = $templating;
    }

    public function getView()
    {
        $this->templating->render('default/view.html.twig');
    }    
}