Symfony 4 TwigFunction 未注册

我正在 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);

    }

}

我在services.yaml中将autowire设置为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.


回首忆惘然
浏览 131回答 1
1回答

幕布斯6054654

你需要返回一个函数数组,你只返回一个。&nbsp; &nbsp; ...&nbsp; &nbsp; public function getFunctions()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new TwigFunction('showControllerName', [$this, 'showControllerName']),&nbsp; &nbsp; &nbsp; &nbsp; ];&nbsp; &nbsp; }&nbsp; &nbsp; ...
打开App,查看更多内容
随时随地看视频慕课网APP