php – 调用时找不到自定义Twig过滤器

我正在尝试创建自己的Twig过滤器.我跟着这个tuto
Symfony Official Book.

但我收到此错误src / Acme / Bundle / StoryBundle / Resources / views / Story / storyList.html.twig中不存在过滤器“avatar”

这是我的AvatarExtension.php

<?php

namespace AppBundle\Twig;

class AvatarExtension extends \Twig_Extension
{
    public function getFilters()
    {

        return array(
            new \Twig_SimpleFilter('avatar', array($this, 'avatar')),
        );

    }

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

    public function avatar($user)
    {
        if ($user->getPicture() && $user->getPicture() != '') {
            return $user->getPicture();
        } else {
            return '/images/default-avatar.jpg';
        }
    }
}

还有我的AppBundle / Resources / config / services.yml

services:
    app.twig.avatar_extension:
        class: AppBundle\Twig\AvatarExtension
        tags:
        – { name: twig.extension }

使用过滤器的模板与Twig扩展名不在同一个包中,但由于它是一项服务,因此它应该不是问题.
以下是我的称呼方式:{{story.author | avatar}}

你知道问题可能是什么吗?

编辑

# Twig Configuration
twig:
    debug:            "%kernel.debug%"
    strict_variables: "%kernel.debug%"
    globals:
      uploadTmpDir: %upload.tmp.relative.dir%

最佳答案 好的,我找到了解决方案.这是services.yml

app.twig.avatar_extension:
        class: AppBundle\Twig\AvatarExtension
        tags:
            - { name: twig.extension }

这是ExtensionClass:

<?php

namespace AppBundle\Twig;

class AvatarExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('avatar', array($this, 'avatarFilter')),
        );
    }

    public function avatarFilter($user)
    {
        if ($user->getPicture() && $user->getPicture() != '') {
            return $user->getPicture();
        } else {
            return '/images/default-avatar.jpg';
        }
    }

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

我想函数名必须有Filter后缀

点赞