It is really excited 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  %}
   <h2> Please place a block in banner region.</h2>
{% else %}
   {{ page.banner }}
{% endif %}

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

 

How to check the if empty the region in twig drupal8?

 

   {% if page.banner is empty  %}

 

 

 

How to print the region in twig drupal8?

 

  {{ page.banner }}

 

 

 

How to use the if else condition in twig drupal8?

 

  {% if page.banner is empty  %}

    <h2> Please place a block in banner region.</h2>

  {% else %}

    {{ page.banner }}

 {% endif %}

 

 

 

How to use nested if else condition in twig drupal8?

 

  {% if page.header  %}

    {{ page.banner }}

  {% elseif  page.banner %}

    {{ page.banner }}

  {% else %}

    <h2> Please pace a block in either header or banner region.</h2>

  {% endif %}

 

 

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

s18

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

 

comments powered by Disqus