【问题标题】:Twig can't find function created inside TwigExtension classTwig 找不到在 TwigExtension 类中创建的函数
【发布时间】:2017-06-08 12:42:08
【问题描述】:

我正在尝试调用在 TwigExtension (Symfony 3.3) 中创建的 Twig 函数。问题是我找不到我做错了什么,我不确定为什么它不起作用

有人知道问题出在哪里吗?

这是我得到的错误:

Unknown "getCurrentLocale" function.

这是我的代码:

树枝扩展:

<?php

namespace AppBundle\Extension;

use Symfony\Component\HttpFoundation\Request;

class AppTwigExtensions extends \Twig_Extension
{
    protected $request;

    public function __construct(Request $request)
    {

        $this->request = $request;
    }

    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('getCurrentLocale', [$this, 'getCurrentLocale']),

        ];
    }

    public function getCurrentLocale()
    {
        dump ($this->request);
        /*
         * Some code
         */
        return "EN";

    }



    public function getName()
    {
        return 'App Twig Repository';
    }
}

服务:

services:

twig.extension:
    class: AppBundle\Extension\AppTwigExtensions
    arguments: ["@request"]
    tags:
      -  { name: twig.extension }

树枝:

{{ attribute(country.country, 'name' ~ getCurrentLocale() )  }}

【问题讨论】:

  • 您是否尝试过bin/console cache:clear,因为即使在开发中,缓存有时仍然是个问题。我看不到任何其他可能会让人感到奇怪的东西——顺便说一句,请求对象已经可以在 twig 中使用app.request 访问。
  • @JennevanderMeer 我删除缓存并且错误仍然存​​在。

标签: php symfony twig twig-extension


【解决方案1】:

那么您对扩展的总体计划是什么。当app.request.locale in twig 返回当前语言环境时,你还需要它吗? (确实如此)

此外,默认情况下@request 服务不再存在。

在 Symfony 3.0 中,我们将通过从 New in Symfony 2.4: The Request Stack 删除请求服务来一劳永逸地解决这个问题

这就是为什么你应该得到类似的东西:

服务“twig.extension”依赖于一个不存在的服务“request”。

所以你做了这个服务?加载了吗?它是什么?您可以使用bin/console debug:container request 查看与request 匹配的所有可用服务名称。

如果你确实需要扩展中的请求对象,如果你打算做更多的事情,你会想要将request_stack 服务与$request = $requestStack-&gt;getCurrentRequest(); 一起注入。

不知何故,代码、symfony 版本和您发布的错误消息不相关。同样在我的测试中,一旦删除了服务参数,它就可以正常工作。自己尝试减少占用空间并使其尽可能简单,在我的情况下是:

services.yml:

twig.extension:
    class: AppBundle\Extension\AppTwigExtensions
    tags:
        -  { name: twig.extension }

AppTwigExtensions.php:

namespace AppBundle\Extension;
class AppTwigExtensions extends \Twig_Extension {
    public function getFunctions() {
        return [
            new \Twig_SimpleFunction('getCurrentLocale', function () {
                return 'en';
            }),
        ];
    }
}

然后从那里拿走,找出什么时候出错。

【讨论】:

  • 感谢您的帮助。我检查了我的服务,发现我有同名的服务。
猜你喜欢
  • 2018-01-29
  • 2019-01-20
  • 1970-01-01
  • 2012-07-12
  • 2017-09-23
  • 2017-05-12
  • 1970-01-01
  • 2015-08-04
  • 2021-07-04
相关资源
最近更新 更多