Twig Data Access

The following blog post shows how to access various data values from fields on a node when creating a custom node override template.  The techniques can be adapted to custom non-node templates as well.

Getting Drupal 8 Field Values in Twig

A few snippets for long-term reference, should the article ever go away:

The Basics

  • {{ node.field_name.0 }} - Rendered display (may need/want to replace 'node' with 'content')
  • {{ node.field_name.0.value }} - Raw value with any HTML escaped (will show on screen as visible HTML)
  • {{ node.field_name.0.value|raw }} - Raw value with unaltered HTML (value marked 'safe', disabling Twig XSS filter)
  • {{ node.field_name.0.value|striptags }} - Raw value shown as plain text with HTML removed

Field Specific Queries

  • {{ node.field_name.summary }} - Summary of a formatted text field
  • {{ node.field_name.[title|alt|height|width] }} - Properties of an image field
            (use only one of the options listed inside square brackets, and don't include brackets)
  • {{ file_url(content.field_name['#items'].entity.uri.value) }} - Image or other file path
  • {{ node.field_name.description }} - File description property
  • {{ node.field_name.fieldDefinition.label }} - Label for a field

Multi-Value Fields

{% if content.field_name[0] %}
  <ul>
  {% for key, item in content.field_name if key|first != '#' %}
    <li>{{ item }}</li>
  {% endfor %}
  </ul>
{% endif %}

Node versus Content

All of the above are assuming you are overriding the standard node template, to which both content and node objects are passed.  According to the blog post author, the content object has all of your "Manage Display" options applied to it, while node is the original unaltered data object.

With other types of Twig templates, you'll have to look at what objects are being passed to it, and if you're building a truly custom template, you'll be the one passing objects from your custom code.  In either case, enabling Twig debugging and using the dump() function can be a big help:

{{ dump(objectname) }}

See the last section of the "A Real Development Environment" page for instructions for enabling Twig debugging.