【问题标题】:Symfony: Unable to load Twig Extension runtimeSymfony:无法加载 Twig 扩展运行时
【发布时间】:2018-06-13 18:15:51
【问题描述】:

我关注 this guide 为 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:containerApp\Twig\AppRuntime 显示为正确的服务。我也尝试将App\Twig\AppRuntime 设置为公共服务,但没有运气。

这可能是什么问题?

【问题讨论】:

  • 您的 Twig 版本是什么? Twig 1.26 中添加了对您正在做的事情的支持。
  • 您是否使用twig.runtime 标记了App\Twig\AppRuntime 服务?
  • 是的,它是twig.runtime 标签。它没有记录在任何地方......
  • 事实上,它记录在您链接的指南中,但在指令的最后打印非常不明显。我第一次做 Twig 扩展时遇到了完全相同的问题,但过了一段时间我终于注意到了:)
  • 你错过了implements RuntimeExtensionInterface

标签: symfony twig


【解决方案1】:

很可能你忘了标记你的树枝扩展服务。

在这里你得到了第一个例子中如何做的解释: https://symfony.com/doc/current/service_container/tags.html

【讨论】:

    猜你喜欢
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多