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 variable, changing its value to true:
{# Conditional logic #} {% set offline = true %} {% if offline == true %} <p>Website is in maintenance mode.</p> {% endif %}
Now resave our template and view the page in the browser. This time, we will see our paragraph displayed.
By now, we are starting to see how control structures within Twig can come in handy to hide or show certain markup within our template based on the value of a variable. This will come in handy when we have certain Drupal regions that we want to display when a block is placed into a region.
The other commonly used control structure in Twig is looping. The for tag is used to loop over each item in a sequence. For our example, let's try looping based on several items and outputting the count.
Open page.html.twig and add the following:
{# Looping #} {% for i in 0 ..10 %} {{ i }} {% endfor %}
If we save our template and view the page in the browser, we will be presented with the count within our loop displaying on the page, starting at 0 and going to 10.
This is a simple loop, and it only demonstrates the use of the for tag. Once we start creating additional Twig templates, we can loop through more complex Drupal variables. More extensive documentation regarding the for tag can be found at http://twig.sensiolabs.org/doc/tags/for.html.