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?
App\Twig\AppRuntime
service withtwig.runtime
? – vstmtwig.runtime
tag. It is not documented anywhere... – spajakimplements RuntimeExtensionInterface
– Piotr