Drupal 8 howto setting a twig variable for a if statement

You are here

To set a twig variable in Drupal 8 so that can add conditional logic to a region, block, node, custom layout display and/or field in the templating system. Below is are some examples on how to do this,

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  striptags 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 1 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 %}