In Drupal 8, I have a content type, that has an "entity_reference" field and I wish to access the referenced node's fields in twig template. the kint() output for the field is: enter image description here

In this list I can't find the referenced node's field values. How can I (if at all possible) load the node or node fields/values in twig?



1 Answer 1


The referenced nodes are inside the list and you can get the first list item with .0, the referenced node with .entity and then the first field value:

For example if you are in a page or node template:

{{ node.field_reference.0.entity.field_in_referenced_node.0.value }}

You can ommit .0 in both cases, when you only want to get the first value.

Other examples could look like this, but your question is unclear exactly where you are:

{{ item.content['#item'].entity.field_in_referenced_node.value }}
{{ elements['#items'].0.entity.field_in_referenced_node.value }}

Edit: Counting the items in multivalue fields

{{ node.field_reference.getvalue|length }}

You can't use count() in twig, because this is not on the whitelist for allowed methods. This uses getvalue() to get the array of the field and then counts the array keys.

  • Thank you, works like a charm! Where can I learn more about what elements are contained/found where with twig? Commented Apr 4, 2016 at 13:23
  • can you tell how can I get the items count ?
    – echo
    Commented Jun 29, 2016 at 8:33
  • i had an entity reference to a menu and this worked for me (in page.html.twig): node.field_related_menu.0.target_id
    – realgt
    Commented Aug 8, 2016 at 14:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.