Skip to main content

Checking Field Content in a Twig File

Date
2023-03-01

A lot of times in our templates, we will want to add wrapper markup around a field output. Assuming it is configured correctly in the display formatter, simply checking for content.field_example will always resolve to TRUE since this is a render array. We can check the node and call the isEmpty() method on the field. And for more completeness, we can ALSO check content.field_example just in case someone removes that field from the display settings for that entity.

{% if not node.field_example.isEmpty() and content.field_example %}
  <div>{{ content.field_example }}</div>
{% endif %}

Related Tech