我正在尝试调用在twigextension(Symfony 3.3(中创建的Twig函数。问题是我找不到我做错了什么,我不确定为什么它不起作用
有人知道问题在哪里?
这是我遇到的错误:
Unknown "getCurrentLocale" function.
这是我的代码:
树枝扩展:
<?php
namespace AppBundleExtension;
use SymfonyComponentHttpFoundationRequest;
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: AppBundleExtensionAppTwigExtensions
arguments: ["@request"]
tags:
- { name: twig.extension }
树枝:
{{ attribute(country.country, 'name' ~ getCurrentLocale() ) }}
因此,您的总体计划是什么。当TWIG中的app.request.locale
返回当前语言环境时,您仍然需要它吗?(它是这样(
也默认情况下,@request
服务不再存在。
在Symfony 3.0中,我们将通过删除请求服务一劳永
这就是为什么您应该得到类似的原因:
服务" twig.extension"对不存在的服务"请求"具有依赖性。
所以您做了这项服务?加载了吗?它是什么?您可以使用bin/console debug:container request
看到所有可匹配request
的服务名称。
如果您确实需要扩展名中的请求对象,则如果您打算做更多的事情,则需要将request_stack
服务与$request = $requestStack->getCurrentRequest();
一起注入。
以某种方式,您发布的代码,Symfony版本和错误消息不关联。同样在我的测试中,一旦删除了服务参数,它就可以了。自己尝试减少足迹并尽可能保持简单,在我的情况下是:
services.yml:
twig.extension:
class: AppBundleExtensionAppTwigExtensions
tags:
- { name: twig.extension }
apptwigextensions.php:
namespace AppBundleExtension;
class AppTwigExtensions extends Twig_Extension {
public function getFunctions() {
return [
new Twig_SimpleFunction('getCurrentLocale', function () {
return 'en';
}),
];
}
}
从那里拿走它,弄清楚它何时出错。