Overview
During the previous units, you could use PHP logic to conditionally assign values to the variables that get injected into the template, or you could write similar logic directly inside the template using Twig code.
The end result is the same, so which approach is recommended?
It's up to you to decide where to provide your logic. If you know PHP and know where and how to write and execute the code necessary to provide or modify the variables before they are injected, you can use PHP.
Otherwise, you have no choice but to write your logic inside the Twig templates.
The general recommendation is that Twig templates should contain very little logic. After all they are front-end templates, and should be most concerned with printing the variables they receive, and not much else.
In a previous example, the check on the {{ number }} value inside the Twig template was perfectly fine:
{# GOOD example of a condition within Twig: no business logic #}
{% if number < 10 %}
<p>{{ message_less }}</p>
{% endif %}However, if you find yourself doing the same to check the role of the current user to determine if you should print the administration menu, for example, is a bad idea.
This kind of (conditional) logic is considered important business logic, not basic display logic, and should happen in PHP as part of the application's security model:
{#
BAD example of a condition within Twig.
This is important business logic that should happen long before
reaching the front-end rendering stage.
#}
{% if current_user.role == "administrator" %}
{{ admin_menu }}
{% endif %}