1
votes

I was following this guide to add a custom Twig extension to Symfony 4 project.

My App\Twig\AppExtension is as follow:

<?php

namespace App\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class AppExtension extends AbstractExtension
{
    public function getFunctions()
    {
        return [
            new TwigFunction('getController', [AppRuntime::class, 'getController'])
        ];
    }
}

And My App\Twig\AppRuntime:

<?php

namespace App\Twig;

use Symfony\Component\HttpFoundation\RequestStack;

class AppRuntime
{
    private $request;

    public function __construct(RequestStack $requestStack)
    {
        $this->request = $requestStack->getCurrentRequest();
    }

    public function getController()
    {
        return $this->request->get('_controller');
    }
}

But If I try to use getController() function in a template, I'm getting this exception: Unable to load the "App\Twig\AppRuntime" runtime.

The following line from Twig template produces this error:

echo twig_escape_filter($this->env, $this->env->getRuntime('App\Twig\AppRuntime')->getController(), "html", null, true);

php bin/console debug:container shows App\Twig\AppRuntime as a correct service. I've also tried setting App\Twig\AppRuntime as a public service, but without luck.

What can be the problem here?

1
What is your version of Twig? Support for what you are doing was added in Twig 1.26.Jason Roman
Have you tagged the App\Twig\AppRuntime service with twig.runtime?vstm
Yes It was twig.runtime tag. It is not documented anywhere...spajak
In fact it is documented in the guide you linked but with very unnoticeable printing at the very end of the instruction. I had exactly the same problem when was doing my Twig extension first time but after some time I noticed it finally :)Jacek Dziurdzikowski
you were missing implements RuntimeExtensionInterfacePiotr

1 Answers

2
votes

Most probably you forgot to tag your twig extension service.

Here you got explanation how to do it in the first example: https://symfony.com/doc/current/service_container/tags.html