You are browsing the Symfony 4 documentation, which changes significantly from Symfony 3.x. If your app doesn't use Symfony 4 yet, browse the Symfony 3.4 documentation.

How to Write a custom Twig Extension

4.1 version

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.

Tip

Before writing your own Twig extension, check if the filter/function that you need is already implemented in the Symfony Twig extensions. Check also the official Twig extensions, which can be installed in your application as follows:

1
$ composer require twig/extensions

Create the Extension Class

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

1
2
3
4
{{ product.price|price }}

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

Create a class that extends the AbstractExtension class defined by Twig and fill in the logic:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// src/Twig/AppExtension.php
namespace App\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class AppExtension extends AbstractExtension
{
    public function getFilters()
    {
        return array(
            new TwigFilter('price', array($this, 'priceFilter')),
        );
    }

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

        return $price;
    }
}

Tip

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.yaml 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.