Symfony News

New in Symfony 4.1: Twig extensions priority

Matt Brunt

Contributed by
Matt Brunt
in #24777.

Twig supports the overloading of filters, functions, global variables, etc. It's not a commonly needed feature, but it's useful to change the behavior of some extension used in your application.

Overloading those elements require to define them in a new Twig extension and register that extension as late as possible to override the other extensions. When using Twig as a standalone templating engine, it's easy to control the order in which extensions are registered. However, in Symfony you don't have any control of this ordering.

In Symfony 4.1, to allow you to overload any Twig element, we've added support for defining priorities in the Twig extensions. This priority mechanism works the same as in other parts of the framework: priority is defined as a positive or negative integer in the priority attribute of the related service tag (twig.extension in this case):

# config/services.yaml
    # ...
        public: false
            # extensions with higher priorities are registered earlier
            - { name: twig.extension, priority: -1024 }

The only caveat is that when defining priorities you cannot rely on service autoconfiguration and must register the Twig extension as a service explicitly to define the priority attribute.

Be trained by Symfony experts - 2018-03-12 Cologne - 2018-03-19 Clichy - 2018-03-19 Clichy

About us

What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...

Find us on Twitter

Find us on Facebook