How to make a Symfony2 Twig Extension

I couldn’t find a decent tutorial online that explained twig extensions in a simple way so for those of you in need here is a step by step guide on how to create a twig extension for Symfony2.

The first thing to know is the difference between twig global, filter and functions (or just how the look in twig templates).


1     {{ global_variable }}


1     {{ 'some sort of text'|filter }}


1     {% function('some variable or text') %}

If you want more information look here:

For the following steps remember to change the ‘Bundle’ and ‘NameBundle’ to your bundles values. Also note that the following code is just for creating filters.

Step 1: Create the filter

Create a file Bundle/NameBundle/Extension/MyTwigExtension.php and use the following code inside it.

 1 <?php
 2 namespace Bundle\NameBundle\Extension;
 3 use Symfony\Component\HttpKernel\KernelInterface;
 4 class MyTwigExtension extends \Twig_Extension
 5 {
 6     public function getFilters()
 7     {
 8         return array(
 9             'uppercase_first_letter' => new \Twig_Filter_Method($this, 'uppercase_first_letter'),
10             'var_dump' => new \Twig_Filter_Function('var_dump')
11         );
12     }
14     function uppercase_first_letter($var){
15         return ucwords($var);
16     }
18     public function getName()
19     {
20         return 'recensus_twig_extension';
21     }
22 }

So I’ve created two filters that I can use in my twig templates, uppercase_first_letter and var_dump. var_dump is already a function within php so that just works without having to create the method within the MyTwigExtension class. uppercase_first_letter require me to create a public method within the class.

Notice the different classes used, Twig_Filter_Method for a custom methods and Twig_Filter_Function for a php method.

Step 2: Register with config

Then you need to add the following code to the bottom of the config file (/app/config/config.yml).

1 services:
2     anywordyouwant.twig.extension.mytwigextension:
3         class: Bundle\NameBundle\Extension\MyTwigExtension 
4         tags:
5             -  { name: twig.extension }

Step 3: Use the filters

Inside your twig templates

1     {{ 'what ever you want'|uppercase_first_letter }}