0

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.