0

I have a content type with a reference field to another content type. This allows an unlimited amount of entries.

I've created a template for this field: field--node--field-my-fields.html.twig

I want to be able to access the fields of my referenced node. Usually you can do this by accessing the entity, but I can't seem to do this.

{% for item in items %}
  {{ kint(item.content) }}
{% endfor %}

I feel like this should be really simple, but I just can't find a way to get access to the fields!

Thanks in advance for any answers.

  • What is being output in kint()? – Jamie Hollern Apr 13 '17 at 13:19
  • @JamieHollern - I can't really say or paste anything here, my browser dies if I try and expand any of the output. – Daniel Dewhurst Apr 13 '17 at 13:31
  • Could you try to use dump() instead and format that and stick it in a dump somewhere then link to it here? – Jamie Hollern Apr 13 '17 at 13:32
  • item.entity.body perhaps? – Clive Apr 13 '17 at 13:41
  • @JamieHollern I can't event dump() item.content out. I'll try item.entity now. – Daniel Dewhurst Apr 13 '17 at 13:52
2

In item.content is a render array and usually you can access a referenced entity in a '#' key (for most display settings):

{{ item.content['#node'].field_name.value }}

Field Object

Another way to get the field values is using the field object in element['#items'] and loop through the FieldItemList:

{% for item in element['#items'] %}
    {{ item.entity.field_name.value }}
{% endfor %}

Then you are independent from the display settings of the field.

For background information see this blog post from Berdir https://www.md-systems.ch/blog/techblog/2017/02/20/twig-and-entity-field-api-or-how-to-take-control-of-nodehtmltwig for the difference between formatted output and the underlying objects. In a field template you don't need to go back to the parent node object, because you can access directly the field object. You can get the parent node from element['#object'] though, if you want to access other fields.

| improve this answer | |
  • item.content['#node'].title.value seems to return null, along with any other field. – Daniel Dewhurst Apr 13 '17 at 14:53
  • kint(item.content['#node']) returns null. I've double checked that I've actually got referenced content too! – Daniel Dewhurst Apr 13 '17 at 15:09
  • Have you configured the display settings of the field to render the entity?. If you only display a label then drupal might not even include the node entity, because it is not needed for that. – 4k4 Apr 13 '17 at 15:20
  • @DanielDewhurst, I added some more information about the field template. – 4k4 Apr 13 '17 at 16:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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