Warning: You are browsing the documentation for Symfony 3.3, which is no longer maintained.

Read the updated version of this page for Symfony 5.3 (the current stable version).

How to Write a custom Twig Extension

How to Write a custom Twig Extension

If you need to create custom Twig functions, filters, tests or more, you’ll need to create a Twig extension. You can read more about Twig Extensions in the Twig documentation.

Create the Extension Class

Suppose you want to create a new filter called price that formats a number into money:

{{ product.price|price }}

{# pass in the 3 optional arguments #}
{{ product.price|price(2, ',', '.') }}

Create a class that extends \Twig_Extension and fill in the logic:

// src/AppBundle/Twig/AppExtension.php
namespace AppBundle\Twig;

class AppExtension extends \Twig_Extension
    public function getFilters()
        return array(
            new \Twig_SimpleFilter('price', array($this, 'priceFilter')),

    public function priceFilter($number, $decimals = 0, $decPoint = '.', $thousandsSep = ',')
        $price = number_format($number, $decimals, $decPoint, $thousandsSep);
        $price = '$'.$price;

        return $price;


Prior to Twig 1.26, your extension had to define an additional getName() method that returned a string with the extension’s internal name (e.g. app.my_extension). When your extension needs to be compatible with Twig versions before 1.26, include this method which is omitted in the example above.


Along with custom filters, you can also add custom functions and register global variables.

Register an Extension as a Service

Next, register your class as a service and tag it with twig.extension. If you’re using the default services.yml configuration, you’re done! Symfony will automatically know about your new service and add the tag.

You can now start using your filter in any Twig template.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.