Scope of “set” in twig templates

Variables set outside block in parent templates, are not overridden with values from child templates, so code like this

{% set pageTitle = 'Homepage' %}
<html>
  <head>
    <title>{{ pageTitle }}</title>
  </head>
  <body>
    {% block body %}
    Welcome, this is {{ pageTitle }}
    {% endblock %}
  </body>
</html>
{% extends 'base.twig' %}
{% set pageTitle = 'My awesome site' %}

{% block body %}
Welcome to <u>{{ pageTitle }}</u>
{% endblock %}

will render as “Welcome to Homepage”, which is not what we want. One way to deal with it is to redefine this variable in every block in child template

{% extends 'base.twig' %}
{% block body %}
{% set pageTitle = 'My awesome site' %}
Welcome to <u>{{ pageTitle }}</u>
{% endblock %}

But this has two main problems: will not work for variable usage outside blocks (like in <title> in code above), and requires to have same reassignment in every block using this variable.

To get values defined in child templates in all blocks and outside them in parent template, we have to modify set statements in base file, to check for defined variables and fallback to default value, like this:

{% set pageTitle = pageTitle|default('Homepage') %}
...

Leave a Reply

Your email address will not be published. Required fields are marked *