Tomek Buszewski
Tomek Buszewski

Reputation: 7935

Twig's custom filters aren't working

I created a simple Twig filter from the docs:

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;
    }

It's registered in the config (since in that file I have a function that works well):

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

But it doesn't work, saying The filter "price" does not exist. How come?

Upvotes: 5

Views: 4376

Answers (2)

herlambang
herlambang

Reputation: 185

Probably you could use my simple example.

class filter:

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';
    }
}

config:

services:
    bundle.twig.price:
        class: Project\Bundle\Twig\Price
        tags:
            - { name: twig.extension }

Upvotes: 1

Mirage
Mirage

Reputation: 31548

Few things first make sure you have this function in the twig class

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

Secondly try changing this to the full class name for debugging then you can change it

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

Upvotes: 3

Related Questions