Search code examples
phpsymfonytwig

Get error while trying to load a twig filter I'm working on


After read the docs I tried my first filter but got this error

The filter "sanitize_for_image_url" does not exist in /var/www/html/src/CategoryBundle/Resources/views/Default/menu.html.twig at line 5.

What I did was:

  • Create a folder under my bundle directory and call it Twig.
  • Under that folder create the file CategoryExtension.php and add this code:

    <?php
    
    namespace CategoryBundle\Twig;
    
    class CategoryExtension extends \Twig_Extension {
    
    public function getFilters() {
        return array(
            new \Twig_SimpleFilter('price', array($this, 'priceFilter')),
        );
    }
    
    public function sanitize_for_image_urlFilter($image) {
        $image = strtolower($image);
        $image = preg_replace('/[^a-z0-9 -]+/', '', $image);
        $image = str_replace(' ', '-', $image);
    
        return $image;
    }
    
    public function getName() {
        return 'category_extension';
    }
    

    }

  • Create a folder inside \CategoryBundle\Resources and called "config" and under config created the file "services.yml" with this content:

    services:
        category.twig.category_extension:
            class: CategoryBundle\Twig\CategoryExtension
            tags:
                - { name: twig.extension }
    
  • Call the filter in my twig template as follow:

    <img src="{{ asset('bundles/dashboard/img/categories/' ~ entity.getName|lower|sanitize_for_image_url ~ '.gif') }}">
    

Did I miss something else?


Solution

  • You're not telling twig about your new filter. You'll also need to modify the getFilters() method of your class.