Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 62 ยท Templates with Twig

Custom Twig Extensions

Add your own Twig filters, functions and tests in Symfony with extensions, attributes and lazy runtime classes, then meet Twig components. Includes a runnable demo.

Twig ships with dozens of filters and functions, but every application eventually needs its own: formatting a price from integer cents, turning a name into initials, rendering a status badge. You could compute these in the controller, but then every controller has to remember to do it. A Twig extension lets you teach Twig new vocabulary once and use it in every template.

This lesson shows the classic extension class, the newer attribute style, the runtime extension pattern for services with dependencies, and an introduction to Twig components for reusable pieces of markup. You should know functions, filters and tests and services. Real Symfony code is read-only; two plain-PHP stand-ins let you run the registration and lazy-loading ideas.

The classic extension

An extension is a class that extends AbstractExtension and returns lists of filters, functions and tests. Each item names the Twig-side word and the PHP callable behind it.

PHP
// src/Twig/AppExtension.php (real Symfony, read-only)
namespace App\Twig;

use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
use Twig\TwigTest;

final class AppExtension extends AbstractExtension
{
    public function getFilters(): array
    {
        return [
            new TwigFilter('price', $this->formatPrice(...)),
            new TwigFilter('initials', $this->initials(...)),
        ];
    }

    public function getFunctions(): array
    {
        return [
            new TwigFunction('badge', $this->badge(...), ['is_safe' => ['html']]),
        ];
    }

    public function getTests(): array
    {
        return [
            new TwigTest('free', fn (int $cents): bool => $cents === 0),
        ];
    }

    public function formatPrice(int $cents, string $currency = '$'): string
    {
        return $currency . number_format($cents / 100, 2);
    }

    public function initials(string $name): string
    {
        $words = preg_split('/\s+/', trim($name)) ?: [];

        return implode('', array_map(fn (string $w): string => strtoupper($w[0]), $words));
    }

    public function badge(string $text): string
    {
        return '<span class="badge">' . htmlspecialchars($text, ENT_QUOTES) . '</span>';
    }
}

Once the class exists, you are done. Symfony's service configuration has autoconfigure: true by default, so any service that extends AbstractExtension is tagged as a Twig extension automatically (see configuring services). In a template:

TWIG
{# real Twig, read-only #}
<p>{{ order.total|price }} for {{ user.name|initials }}</p>
{{ badge(order.status) }}
{% if order.total is free %}No charge{% endif %}

php bin/console debug:twig lists every filter, function, test and global, including yours, which is a quick way to confirm registration.

Options that matter: escaping and context

Because auto-escaping is on, the output of your filter is escaped again when printed. Usually that is what you want. When your PHP code builds trusted HTML (like badge() above, which escapes its own input), tell Twig not to escape it again with the option 'is_safe' => ['html']. Mark a callable safe only if every code path escapes untrusted data, or you create a cross-site scripting hole.

Other options you will meet:

  • needs_environment: true passes the Twig Environment as the first argument.
  • needs_context: true passes the whole template context as the first argument (after the environment, if both are set).
  • is_variadic: true collects remaining arguments into an array.
  • deprecation_info marks a filter as deprecated with a helpful message.

Prefer pure functions of their arguments. A filter that quietly reads global state or the context is hard to test and hard to understand from the template.

Runtime extensions: lazy loading with dependencies

An extension class is created whenever Twig starts, even on pages that never use its filters. That is fine for cheap pure functions, but costly when the extension depends on services such as a database repository, a translator or an HTTP client. Twig's answer is the runtime pattern: the extension class stays tiny and only describes the names, pointing at a separate runtime class. Twig asks the container for the runtime object only when a template actually calls the filter.

PHP
// src/Twig/CurrencyExtension.php (real Symfony, read-only)
namespace App\Twig;

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

final class CurrencyExtension extends AbstractExtension
{
    public function getFilters(): array
    {
        return [
            new TwigFilter('convert', [CurrencyRuntime::class, 'convert']),
        ];
    }
}
PHP
// src/Twig/CurrencyRuntime.php (real Symfony, read-only)
namespace App\Twig;

use App\Service\ExchangeRates;
use Twig\Extension\RuntimeExtensionInterface;

final class CurrencyRuntime implements RuntimeExtensionInterface
{
    public function __construct(private ExchangeRates $rates)
    {
    }

    public function convert(int $cents, string $to): string
    {
        return number_format($cents * $this->rates->for($to) / 100, 2) . ' ' . $to;
    }
}

The callable [CurrencyRuntime::class, 'convert'] names a class, not an object. Symfony makes every service that implements RuntimeExtensionInterface available to Twig through a service locator, so ExchangeRates is only built when a template uses convert. For services with dependencies, this is the recommended style.

flowchart LR
    T["Template<br/>{{ 100|convert('EUR') }}"] --> E["Twig Environment"]
    E --> X["CurrencyExtension<br/>(names only, cheap)"]
    E -->|"first use only"| L["Runtime loader"]
    L --> C["Service container"]
    C --> R["CurrencyRuntime<br/>+ ExchangeRates"]

The extension only names the filter; the runtime object with real dependencies is created lazily when a template uses it.

The attribute style

Recent versions of Twig and Symfony let you skip the extension class: put an attribute on a method of any service, and the filter or function is registered for you. Twig 3.21 introduced #[AsTwigFilter], #[AsTwigFunction] and #[AsTwigTest], and Symfony 7.3 added the autoconfiguration that picks them up. Check your installed versions before relying on them; on older versions use the extension class above.

PHP
// src/Twig/Formatting.php (real Symfony, read-only)
namespace App\Twig;

use Twig\Attribute\AsTwigFilter;
use Twig\Attribute\AsTwigFunction;

final class Formatting
{
    #[AsTwigFilter('price')]
    public function price(int $cents): string
    {
        return '$' . number_format($cents / 100, 2);
    }

    #[AsTwigFunction('stars')]
    public function stars(int $rating): string
    {
        return str_repeat('*', $rating) . str_repeat('-', 5 - $rating);
    }
}

Each attribute accepts the same options as the Twig* classes (safety, context, deprecation). Because this class is a normal service, constructor injection works, and the container creates it lazily like any other service that is needed. The attribute style is the least code, and it keeps the template name next to the code it calls.

How registration works: a stand-in

Symfony's compiler pass finds extension services and hands them to Twig's Environment. The stand-in below does the same in a few lines. Extensions return a map of filter or function names to [callable, isSafe] pairs. A tiny renderer evaluates {{ ... }} expressions and escapes the result unless the last callable was flagged safe. Watch what happens with a callable that returns HTML but is not flagged safe.

PHP Registering extensions and the is_safe flag (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Read the last two lines closely. bold escapes its own input and is flagged safe, so the tag reaches the page. wrap_b returns the same kind of markup but is not flagged safe, so the engine escapes it and the user sees literal &lt;b&gt; text. The safe flag is a promise from you, the extension author, that the output cannot carry unescaped user input.

The lazy runtime idea: a stand-in

The second stand-in shows the point of runtime extensions: names are registered cheaply, while the object with dependencies is created only on first use, and only once. It uses a PHP attribute to mark filter methods, which is how the attribute style discovers them.

PHP Attribute discovery and lazy runtime (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first page registers the filter name but builds nothing: no [container] lines. The second page builds the runtime and its dependency exactly once, on the first call, and reuses them for the other two prices. Symfony's service locator gives you that behaviour for runtime extensions.

Twig components

Filters and functions return strings. For repeated chunks of markup with logic, such as an alert box, a product card or a modal, Symfony offers Twig components from the UX project (composer require symfony/ux-twig-component). A component is a PHP class that holds the data and optional logic, plus a Twig template that renders it.

PHP
// src/Twig/Components/Alert.php (real Symfony, read-only)
namespace App\Twig\Components;

use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent]
final class Alert
{
    public string $type = 'info';
    public string $message = '';

    public function iconClass(): string
    {
        return match ($this->type) {
            'success' => 'icon-check',
            'danger' => 'icon-warning',
            default => 'icon-info',
        };
    }
}
TWIG
{# templates/components/Alert.html.twig (real Twig, read-only) #}
<div class="alert alert-{{ type }}">
    <span class="{{ this.iconClass }}"></span>
    {{ message }}
    {% block content %}{% endblock %}
</div>

You use it with an HTML-like tag in any template. Public properties become props, and the content between the tags fills the content block:

TWIG
{# real Twig, read-only #}
<twig:Alert type="success" message="Product saved." />

<twig:Alert type="danger">
    <twig:block name="content"><a href="{{ path('support') }}">Contact support</a></twig:block>
</twig:Alert>

A component can be a plain presentation helper like this one, or it can be a service with injected dependencies (components are services, so autowiring works). Choose by the shape of the job:

You need Use
Transform a value in place A filter
Compute a value from arguments A function
Check a condition A test
Shared markup with props and logic A component
Shared markup without logic An include or macro from the layouts lesson

Habits that keep extensions healthy

  • Keep each filter small and pure; put real business logic in services and have the filter call them.
  • Put dependency-carrying code in a runtime class so pages that do not use it stay fast.
  • Write a unit test for the PHP callable, not for the template. A filter is just a PHP method.
  • Mark output safe only when the callable escapes everything untrusted itself.
  • Group related helpers per extension (MoneyExtension, TextExtension) instead of one giant class.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What do you extend to create the classic custom Twig extension?

    AbstractExtension lets you return filters, functions and tests from getFilters(), getFunctions() and getTests(). Autoconfiguration registers it for you.
  2. 2. Why use a runtime extension (RuntimeExtensionInterface)?

    The extension class stays tiny and only names the filters. The container builds the runtime service lazily on first use.
  3. 3. What does 'is_safe' => ['html'] tell Twig about a filter?

    It is a promise from the author. If the callable does not escape untrusted input, it opens an XSS hole.
  4. 4. Which tool is best for a reusable alert box with props and a bit of PHP logic?

    Twig components pair a PHP class (props and logic) with a template, and are used with the twig:Name syntax.
  5. 5. How can you confirm that your new filter is registered?

    debug:twig lists all filters, functions, tests and globals available to templates.

Summary

  • A Twig extension teaches Twig new filters, functions and tests; extend AbstractExtension and Symfony registers it automatically.
  • Use is_safe only when your callable escapes untrusted data itself.
  • Runtime extensions keep the extension class tiny and create the dependency-carrying object lazily.
  • Newer Twig and Symfony versions support #[AsTwigFilter], #[AsTwigFunction] and #[AsTwigTest] on service methods; check your versions first.
  • Twig components bundle markup, props and logic for reusable UI pieces.

Next up: Assets, AssetMapper and Webpack Encore.