Drupal 8 TWIG template check field is empty

Playing around with Paragraphs I needed to display or hide a bit of a template based on a text field length being greater than 0.

First try Check length…

{% if content.field_option_alert|length > 10}
  length:{{ content.field_option_alert|length }}
{% endif %}

Checking the length of the field always returns 2 for empty field and does not work.

These suggestions also return 2 or a ‘true’ to the field being set

{% if content.field_option_alert is not empty %}
{% if content.field_option_alert.value is not empty %}
{% if content.field_option_alert.value %}
{% if content.field_option_alert|length > 0}

Printing the field showed an empty string in the source, yet it always returned string length of 2.

Final solution

Check the length of the rendered trim field.

{{ content.field_option_alert|render|trim|length }}
Was this article helpful?
YesNo