4

我从文档中创建了一个简单的 Twig 过滤器:

public function getFilters() {

        return array(
            'price' => new \Twig_Filter_Method($this, 'priceFilter'),
        );
    }


    public function priceFilter($number, $decimals = 0, $decPoint = '.', $thousandsSep = ',')
    {
        $price = number_format($number, $decimals, $decPoint, $thousandsSep);
        $price = '$' . $price;

        return $price;
    }

它已在配置中注册(因为在该文件中我有一个运行良好的功能):

services:
    sybio.twig_extension:
        class: %sybio.twig_extension.class%
        tags:
            - { name: twig.extension }

但它不起作用,说The filter "price" does not exist。怎么来的?

4

2 回答 2

3

几件事首先确保您在 twig 类中具有此功能

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

其次尝试将其更改为完整的类名以进行调试,然后您可以更改它

class: %sybio.twig_extension.class%class: Acme\DemoBundle\Twig\AcmeExtension

于 2013-01-26T07:31:37.057 回答
1

可能您可以使用我的简单示例。

类过滤器:

namespace Project\Bundle\Twig;

class Price extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            'price' => new \Twig_Filter_Method($this, 'priceFilter'),
        );
    }

    public function priceFilter($arg)
    {
        return number_format($arg);
    }

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

配置:

services:
    bundle.twig.price:
        class: Project\Bundle\Twig\Price
        tags:
            - { name: twig.extension }
于 2013-01-26T07:47:37.140 回答