Skip to main content

Drupal 8 howto setting a twig variable for a if statement

Member for

3 years 1 month
Submitted by admin on

To set a twig variable in Drupal 8 to add conditional logic to a region, block, node, custom layout display and field in the templating system. Below is are some examples of how to make these changes in a twig template file.

Does the variable have any content at all

  
{% set content_variable = content.field_or_content|render|trim  %}
{% if content_variable %}
//-- print result if true
{% else %}
//-- print result if false
{% endif %}

Sometimes the content only has HTML tags use strip tags can remove it

  
{% set content_variable = content.field_or_content|render|striptags %}
{% if content_variable %}
//-- print result if true
{% else %}
//-- print result if false
{% endif %}

If a field is a boolean type, use "in" this example below will only work when you create the field type you use one instead of the default "on"

 
{% set content_variable = content.field_or_content[0] %}
{% if '1' in content_variable %}
//-- print result if true
{% else %}
//-- print result if false
{% endif %}