Drupal 8 Twig
Blog

How to use if else statement in twig Drupal 8?

It is really exciting to work with twig in Drupal 8. Here we are going to find out how to use if else condition in twig in page.html.twig or any *.twig files. 

We are having a region called ‘banner’, which is already defined in your theme.info.yml. In the page.html.twig we need to check that if there is any content is present in the ‘banner’ region. For that, we need to use the if-else condition in our *.html.twig file. So we need to use the following code on your page.html.twig file.

{% if page.banner is empty  %}
   

Please place a block in the banner region.

{% else %}    {{ page.banner }} {% endif %}

From the above code snippet, you can understand the following points, 

How to check the if empty the region in drupal 8 twig?

   {% if page.banner is empty  %}

How to print the region in drupal 8 twig?

  {{ page.banner }}

How to use the if else condition in drupal 8 twig?

  {% if page.banner is empty  %}

Please place a block in banner region.

  {% else %}     {{ page.banner }}  {% endif %}

How to use nested if else condition in drupal 8 twig?

 {% if page.header  %}

    {{ page.banner }}

  {% elseif  page.banner %}

    {{ page.banner }}

  {% else %}

Please pace a block in either header or banner region.

  {% endif %}

 

Below is the CodeBase from page.html.twig from one of the "Bartik" Theme

s18

So we understood how to use the if else in twig drupal 8.

Related

How to Render Twig Blocks