0

我正在尝试为 Twig 创建一个新函数,并在 Symfony2 中创建一个 Twig 扩展。该服务已注册并正确注入容器(因此我可以引用该response对象),但它没有找到该功能。

这是扩展名:

namespace MyProject\Bundle\MyBundle\Twig\Extensions;

use Twig_Extension,
    Twig_Function_Method;

use Symfony\Component\DependencyInjection\ContainerAwareInterface,
    Symfony\Component\DependencyInjection\ContainerInterface;


class TwigUiExtensions extends Twig_Extension implements ContainerAwareInterface
{
    protected $container;

    public function setContainer(ContainerInterface $container = NULL)
    {
        $this->container = $container;
        return $this;
    }

    public function getContainer()
    {
        return $this->container;
    }

    public function getFunctions()
    {
        return array(
            'defaultBodyClasses'    =>  new Twig_Function_Method($this, 'defaultBodyClassesFunction')
        );
    }

    private function _getControllerName()
    {
        $pattern = "#Controller\\\([a-zA-Z]*)Controller#";
        $matches = array();
        preg_match($pattern, $this->getContainer()->request->get('_controller'), $matches);
        return strtolower($matches[1]);
    }

    private function _getActionName()
    {
        $pattern = "#::([a-zA-Z]*)Action#";
        $matches = array();
        preg_match($pattern, $this->getContainer()->request->get('_controller'), $matches);
        return $matches[1];
    }

    public function defaultBodyClassesFunction($userClasses = NULL)
    {
        $classes = array();
        $classes[] = $this->_getControllerName();
        $classes[] = $this->_getActionName();
        if ($userClasses) {
            $classes[] = $userClasses;
        }
        return join(' ', $classes);
    }

    public function getName()
    {
        return 'ui_extensions';
    }
}

在我的 Twig 文件中,当我调用 时defaultBodyClasses(),Symfony 给了我一个错误:The function "defaultBodyClasses" does not exist并引用了我正在调用该函数的 Twig 文件。

任何想法可能会发生什么?

谢谢,内特


编辑:

这是服务定义:

<parameters>
    <parameter key="myproject.twig.extensions.ui_extensions.class">MyProject\Bundle\MyBundle\Twig\Extensions\TwigUiExtensions</parameter>
</parameters>

<services>
    <service id="myproject.twig.extensions.ui_extensions" class="%myproject.twig.extensions.ui_extensions.class%">
        <call method="setContainer">
            <argument type="service" id="service_container" />
        </call>
    </service>
</services>
4

1 回答 1

1

您忘记指定此服务是 Twig 扩展:

<parameters>
    <parameter key="myproject.twig.extensions.ui_extensions.class">MyProject\Bundle\MyBundle\Twig\Extensions\TwigUiExtensions</parameter>
</parameters>

<services>
    <service id="myproject.twig.extensions.ui_extensions" class="%myproject.twig.extensions.ui_extensions.class%">
        <tag name="twig.extension" />
        <call method="setContainer">
            <argument type="service" id="service_container" />
        </call>
    </service>
</services>
于 2012-09-04T12:40:06.133 回答