How can I create a symfony twig filter?

Viewed 24149

For instance my bundle namespace is Facebook\Bundle\FacebookBundle\Extension.

Using this how can I create a twig extension ?

4 Answers

None of the given answers worked for Symfony 3.4 and above.

For Symfony 3.4, 4.x

// src/TwigExtension/customFilters.php 

namespace App\TwigExtension; 
use Twig\TwigFilter; 

class customFilters extends \Twig_Extension { 

    public function getFilters() { 
        return array( 
            new TwigFilter('base64_encode', array($this, 'base64_en'))
        );
    }

    public function base64_en($input) {
       return base64_encode($input);
    }
}

And then in your twig template you can do

{{ 'hello world' | base64_encode }}

Thats it. For detailed explanation, you could check out the reference.

Reference: DigitalFortress

Related