English spoken conference

Symfony 5: The Fast Track

A new book to learn about developing modern Symfony 5 applications.

Support this project

New in Twig: Deprecated tag

Contributed by
Yonel Ceruto
in #2696.

Deprecations are the key of our backward compatibility promise and allow a smooth upgrade process for Symfony apps. However, you can only trigger deprecations in PHP code, so you can't warn users when some Twig template or block are going to be deprecated.

That's why in Twig 1.36 and 2.6 we've added a new {% deprecated %} tag. First, it allows to deprecate entire templates, which is used in the following example to warn users that base.twig will be replaced by layout.twig:

1
2
3
{# base.twig #}
{% deprecated 'The "base.twig" template is deprecated, use "layout.twig" instead.' %}
{% extends 'layout.twig' %}

In addition to entire templates, you can also deprecate individual blocks:

1
2
3
4
5
6
7
8
{% block user_menu %}
    {% deprecated 'The "user_menu" block is deprecated, use "user_menu_actions" instead.' %}
    {{ block('user_menu_actions') }}
{% endblock %}

{% block user_menu_actions %}
    {# ... #}
{% endblock %}

Whenever Twig finds a {% deprecated %} tag, it generates a deprecation notice (via a call to PHP's trigger_error() function) so you can see those deprecations alongside the other normal Symfony deprecations.

Comments

I'm not sure to understand the first example. Code is using directly the "layout" template, how can you keep BC with that?
@Massimiliano in the first example, the template that will be removed is "base.twig". That's why you move all its contents to the new template ("layout.twig"), extend from it (to not break apps still using the old template) and add the "deprecated" tag to warn users about this change.
@Massimiliano the deprecated template here is not `layout.twig` but `base.twig`. The BC layer is that we don't remove `base.twig` immediately. Instead, we trigger a deprecation warning to warn you that you need to migrate your code (to be ready for the next major version removing `base.twig`)
Does it also works for macros?
@Gregor Well, you can use this tag in any place a tag can be used. So you can use it inside a macro, to trigger a warning when the macro gets called (we cannot trigger a warning when it is imported without being used)

Comments are closed.

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