Drupal - How to check a boolean value in twig templates?

Time for another promotion of my blogpost from a while ago :)

https://www.md-systems.ch/en/blog/techblog/2017/02/20/twig-and-entity-field-api-or-how-to-take-control-of-nodehtmltwig

The relevant part:

Only display a field if a checkbox is checked, optionally with custom wrapping HTML.

{% if node.field_checkbox.value %}
   <div class="only added when there are values">
  {{ content.field_name }}
  </div>
{% endif %}

You don't need == '1' or same as or anything like that, because it directly evaluates as to a boolean value. I also wouldn't recommend to use type safe checks with content entities because they are not type safe. Values are stored in the database and anything coming out from there is a string but sometimes values might not be. The boolean field is actually the perfect example for that, it is a string one, aka a nice mix of 3 different data types.


Checkbox fields value check in Twig templates for drupal 8:

{% if node.field_checkbox['#items'].value == '1' %}
  <div class="only added when there are values">
    {{ content.field_name }}
  </div>
{% endif %}

Thats works fine for me.


If you create the Boolean field in the content type then this worked for me

{% if node.field_boolean.value == 1 %} {{ page.contact_form }} {% endif %}

and also if you have boolean field in a paragraph then this worked for me

{% if content.field_boolean['#items'].value == 1 %} {{ content.field_description }} {% endif %}