Skip to main content
  • Guides & Documentation

Knowledgebase

Featured articles, how-to guides and quick tips.

Paragraphs module Drupal 8 - Twig IF statements for field values

Conditional IF statements for field values in Twig aren't really a challenge in Drupal 8. In fact, using conditional statements in nodes or page templates is quite easy.

However, when using the Paragraphs module for Drupal 8, there is a difference in how conditional statements need to be approached.

The Paragraphs module renders all content using the standard {{ content }} variable.

However, to get the value of a specific field for a conditional statement, the following should be used:

{% if paragraph.field_custom.value == 1 %}

{% endif %}

This is slightly different from the standard content.field_custom.value statement that you would ordinarily use in node templates:

{% if content.field_custom.value == 1 %}

{% endif %}

But of course, there is also the possibility that you'll need to use a condition IF / OR statement. For instance, you might have a field which could return multiple values.

A practical use case example of this would be a boolean vs an integer or computed field.

Unlike a boolean, which is fairly simple (as explained above), it's a little trickier to get an If/Or statement in Paragraphs twig templates. Or rather, the syntax is going to be slightly different.

A boolean, in simple terms, is a basic toggle between True or False. But for an integer-type field, you could potentially have multiple values.

In this case, we're going to use a slightly different syntax, which is:

{% if paragraph.field_custom.value in ['1', '2', '3', '4'] %}

Just switch out the bolded text for your specific values.

An example of such code in use might look like this:

{% if paragraph.field_custom.value in ['1', '2', '3', '4'] %}

{{ content.field_custom }}

{% else %}

{{ something else }}

{% endif %}

But if all you're looking for is to determine whether the specific field has any value at all (i.e. is not left blank or empty), use the following syntax instead:

{% if content.field_custom|render %}

{{ content.field_custom }}

{% endif %}

This is all great. But what if you need a conditional for when the field actually is empty? This is great for markup that you might need to print if all fields are populated, except one. Here's a great syntax that works in Paragraph templates:

{% if paragraph.field_custom is empty %}

{{ do something }}

{% endif %}

Happy Drupal theming!