3

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".

roggy
  • 33
  • 3

1 Answers1

0

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');
    }    
}
jkucharovic
  • 4,214
  • 1
  • 31
  • 46
  • Thanks, but how did you know what interface to use? Where can I check it? If I run "bin/console debug:container" then I have: 'templating alias for "templating.engine.twig" ' . So why and how EngineInterface? – roggy Aug 04 '17 at 07:19
  • @roggy using `bin/console debug:container templating` gives you [hint of autowiring types](https://i.stack.imgur.com/7fkeN.png). – jkucharovic Aug 04 '17 at 07:49