我正在用Symfony 4写一个Twig函数,但我无法让它工作.
扩展类
<?php
namespace App\Twig;
use App\Utils\XXX;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class XXXExtension extends AbstractExtension
{
/**
* @return array|TwigFunction|TwigFunction[]
*/
public function getFunctions()
{
return new TwigFunction('showControllerName', [$this, 'showControllerName']);
}
public function showControllerName($sControllerPath)
{
return XXX::getControllerName($sControllerPath);
}
}我已经将autowire设置为services.yaml中的true,但万一我也尝试过这样做的话:
App\Twig\XXXExtension:
public: true
tags:
- { name: twig.extension }在html.twig中的使用
{% set controllerName = showControllerName(app.request.get('_controller')) %}之后我得到的回应是:
HTTP 500 Internal Server Error
Unknown "showControllerName" function.发布于 2019-09-23 14:09:22
您需要返回一个函数数组,您只返回一个函数。
...
public function getFunctions()
{
return [
new TwigFunction('showControllerName', [$this, 'showControllerName']),
];
}
...https://stackoverflow.com/questions/58064130
复制相似问题