Custom Twig Filters Don't Work

I created a simple Twig filter from documents:

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 is registered in the configuration (since in this file I have a function that works well):

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

But that does not work, saying The filter "price" does not exist. Why?

+5
source share
2 answers

A few things first make sure you have this feature in the twig class

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

Secondly, try changing this to the fully qualified class name for debugging, then you can change it

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

+4
source

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

configurations:

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

All Articles