SymfonyWorld Online 2021 Winter Edition December 9 – 10, 2021 100% Online +20 talks and workshops

New in Symfony 4.1: Twig extensions priority

Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.

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.

Help the Symfony project!

As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.


Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.