Skip to content

Instantly share code, notes, and snippets.

@MGHollander
Last active July 1, 2020 10:23
Show Gist options
  • Save MGHollander/c27fd6e70303f600817808fd3b878843 to your computer and use it in GitHub Desktop.
Save MGHollander/c27fd6e70303f600817808fd3b878843 to your computer and use it in GitHub Desktop.
Common ways to get field values in twig templates in Drupal 8
{# Get field_text #}
{{ content.field_text }}
{# Get content of field_text #}
{{ content.field_text.0 }}
{# Get the path of an image / file #}
{{ file_url(content.field_image[0]['#media'].field_media_image.entity.uri.value) }}
{# Get the alt value of an image #}
{{ content.field_image[0]['#media'].field_media_image.alt }}
{# When a field is of the type ListStringItem (https://api.drupal.org/api/drupal/core%21modules%21options%21src%21Plugin%21Field%21FieldType%21ListStringItem.php/class/ListStringItem/8.8.x).
Drupal classes have proper methods to access the values they store, so the correct approach would be
to use them. In this case, you can access the FieldItemList object that this field stores with
content.field_header_background_color['#items']. You can't render that, but you can access (most of)
its methods, including the magic getter for the value. So, to get the stored value (and not the
rendered value), you can use: #}
{{ content.field_header_background_color['#items'].value }}
{#
You can find more on this page: https://blog.usejournal.com/getting-drupal-8-field-values-in-twig-22b80cb609bd
#}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment