Common Twig Patterns
Patterns
Here is a list of common patterns to display drupal fields and data. All patterns are using the entity type node, though the patterns should also work with other entity types. We are just using node as an example.
If field is set
For checking if a field is entered, use this pattern. Using a field with machine name field_my_field for example:
{% if node.field_my_field|length %}
My field exists
{% endif %}Text field
For a text field with the machine name field_txt for example:
{# Get text value of text field #}
{{ node.field_txt.value }}Formatted text field
For a text field with the machine name field_ftxt for example:
{# Render the formatted text field as HTML #}
{{ node.field_ftxt.processed|raw }}Note the use of the field value "processed" instead of "value". This will use the processed value of the text formatter which will be safer than using the raw "value", especially when using the |raw filter.
(Caution: The |raw filter does not escape output and is usually unsafe.)
Images
For a image field with the machine name field_image for example:
{# Render the image with alt tag #}
<img src="{{ file_url(node.field_image.entity.uri.value) }}" alt="{{ node.field_image.alt }}">For a media reference field to an image media type with machine name field_media for example:
{# Render the image with alt tag #}
<img src="{{ file_url(node.field_media.entity.field_media_image.entity.uri.value) }}" alt="{{ node.field_media.entity.field_media_image.alt }}">Link fields
For a link field with the machine name field_link for example:
{# Render the link as an anchor tag #}
<a href="{{ node.field_link.0.url }}">{{ node.field_link.title }}</a>Entity reference
For a entity reference field with the machine name field_er for example:
{% Render fields of the reference entity by appending the field data after 'node.field_er.entity' %}
{% For example render a plain text field from a referenced entity %}
{{ node.field_er.entity.field_txt.value }}Paragraph entity reference field
For a paragraph entity reference field with machine name field_paragraph, follow this pattern to render each paragraph in the reference field.
{% for paragraph in node.field_paragraph %}
<p>{{ paragraph.entity.field_text.value }}</p>
{% endfor %}Taxonomy entity reference field
To get the selected taxonomy terms name for a field with machine name field_tax follow this pattern.
{# Taxonomy term name #}
{{ node.field_tax.entity.name.value }}Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion