Control structures
There will be situations while theming with Twig where we will need to check whether a variable is True
or False
, or to loop through a variable to output multiple values contained in an array.
Control structures in Twig allow us to account for these types of functions using {%... %}
blocks to test for expressions and traverse through variables that contain arrays. Each control structure contains an opening and closing tag, like PHP logic. Let's look at a couple of the most commonly used control structures, starting with the if
tag used to test an expression.
Open page.html.twig
and add the following:
{# Conditional logic #} {% set offline = false %} {% if offline == true %} <p>Website is in maintenance mode.</p> {% endif %}
If we save our template and refresh the browser, we will not see anything displaying yet. The reason is that the offline
variable is currently set to false
and we are checking to see whether it is true
.
Open page.html.twig
and edit the offline...