Checking for the existence of a field value in Twig
Twig syntax is new for most Drupalists, and learning how to check for the existence of a field value is a valuble skill for anyone building a Drupal 8 theme. For example, consider the case where there is an optional text field called "Photo caption" on a content type. If the content author populates the "Photo caption" field, then it should be output as follows:
<figcaption>{{ content.field_photo_caption }}</figcaption>
But what if the content author chooses not to populate the "Photo caption" field? Using the above code, an empty <figcaption>
tag will still be rendered on the page.
There are many code snippets available about checking for the existence of the entire {{ content }}
like this:
{% if content %}<br> {{ content }}<br>{% endif %}
Unfortunately, this does not work exactly the same way for fields within the {{ content }}
. The solution is to check for the existence of the rendered field.
{% if content.field_photo_caption|render %}<br> <figcaption>{{ content.field_photo_caption }}</figcaption><br>{% endif %}
Using this method, the <figcaption>
tag and value will only be rendered if the "Photo caption" field has been populated.
Resources: