Twig Extensions
02 / 02

Twig Extensions: Filters, Functions & Tests

Twig Extensions: Filters, Functions & Tests

A Twig extension is a PHP class implementing AbstractExtension that adds custom functionality -- filters, functions, tests, tags, or global variables -- beyond what Twig ships with. Twig's own built-in features (if/for/upper/lower) are themselves implemented via this same extension mechanism.

Custom Filters

class CurrencyExtension extends AbstractExtension
{
    public function getFilters(): array
    {
        return [
            new TwigFilter('price', [$this, 'formatPrice']),
        ];
    }

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

{# template usage -- identical to Twig's own built-in filters #}
{{ product.priceInCents|price }}

Functions vs. Filters

{# Filter: transforms an EXISTING value via pipe syntax #}
{{ user.name|upper }}

{# Function: called with its own arguments, no clear "subject" value #}
{{ current_user() }}
{{ has_permission('edit_post', post) }}

Custom Tests

public function getTests(): array
{
    return [
        new TwigTest('expensive', function (Product $product) {
            return $product->getPriceInCents() > 10000;
        }),
    ];
}
{# reads more naturally than an inline numeric comparison #}
{% if product is expensive %}Premium item{% endif %}

Global Variables

public function getGlobals(): array
{
    // Available in EVERY template with no need to pass it in
    // from each controller's render() call individually
    return ['app_version' => '2.4.1'];
}

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free