我按照本指南向 Symfony 4 项目添加自定义 Twig 扩展。
我的
App\Twig\AppExtension
如下:
<?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'])
];
}
}
还有我的
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');
}
}
但是如果我尝试在模板中使用
getController()
函数,我会收到此异常:
无法加载“App\Twig\AppRuntime”运行时。
Twig 模板中的以下行会产生此错误:
echo twig_escape_filter($this->env, $this->env->getRuntime('App\Twig\AppRuntime')->getController(), "html", null, true);
php bin/console debug:container
将 App\Twig\AppRuntime
显示为正确的服务。我也尝试过将 App\Twig\AppRuntime
设置为公共服务,但没有成功。
这里可能出现什么问题?
很可能您忘记标记您的树枝扩展服务。
您在第一个示例中得到了如何执行此操作的说明: https://symfony.com/doc/current/service_container/tags.html
要将评论放入答案中,此错误有两种解决方案。
RuntimeExtensionInterface
class AppRuntime implements RuntimeExtensionInterface
App\Twig\AppRuntime:
autoconfigure: true
将
twig.runtime
标签添加到运行时服务
App\Twig\AppRuntime:
tags:
- { name: twig.runtime }
我刚刚解决了这个问题,我的情况有所不同,让我把它留在这里,以防它对任何人有帮助。
我得到:
Unable to load the "MyCustomFunctions" runtime in "main" at line 1
我加载函数的方式不是在扩展内,而是一个接一个地加载,如下所示:
$twig->addFunction(new TwigFunction('print', 'MyCustomFunctions::print'));
这是我作为类方法的函数定义
MyCustomFunctions
:
// just as an easy to test example
public function print($var = '') {
return print_r($var, true);;
}
解决方案 问题是我加载函数的方式与函数声明不一致。我忘记了函数声明
public static function
,其中有 static
。现在它与加载函数时使用的 ::
可调用相匹配。
很明显,一旦你看到它,但从错误消息来看却非常不明显......我花了很长时间才弄清楚这一点。