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 %}
  {{ content }}
{% 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 %}
  <figcaption>{{ content.field_photo_caption }}</figcaption>
{% endif %}

Using this method, the <figcaption> tag and value will only be rendered if the "Photo caption" field has been populated.

An alternate way of writing this code using the same concept is:

{% set field_photo_caption = content.field_photo_caption|render %}
{% if field_photo_caption %}
  <figcaption>{{ field_photo_caption }}</figcaption>
{% endif %}

Resources:

Comments

I find that setting variables for field content at the top of the tempalte file &emdash; or above the condition for added context &emdash; makes it easier to theme later when more [optional] fields might be added.

{% set field_photo_caption = content.field_photo_caption|render %}

{% if field_photo_caption %}
<figcaption>{{ content.field_photo_caption }}</figcaption>
{% endif %}

Submitted by Erik Baldwin (not verified) on Tue, 03/29/2016 - 13:39