I have created one custom block having reference entity field. I have two templates to render design. One is 'block--bundle--block_name.html.twig' and another one is 'field--field-field_name.html.twig'.
Inside block--bundle--block_name.html.twig I have below code with some custom HTML-
{% block content %} {{ content }} {% endblock %}And field--field--field-field_name.html.twig contains below with some custom HTML-
{% for item in items %}
{{ item.content }}
{% endfor %}In field level template (field--field--field-field_name.html.twig), {{ item.content }} contains node object and I want to access/print the node title, image and few other fields on the page.
I have tried different ways to track item.content array but unable to get the values. Please let me know if anyone has done this before.
Thanks,
Comments
Found it
https://drupal.stackexchange.com/questions/233977/access-a-referenced-no...
#user
same works for user objects
#media
Thanks, you saved my day.
This is for media in field.html.twig ()
{% for item in items %}<div class="item-video" data-merge="1"><a class="owl-video" href="{{item.content['#media'].field_media_oembed_video.value}}"></a></div>
{% endfor %}
Solved!
Thank you, @narinlab!
I was trying to get an image from within a field--paragraph--field-selector.html.twig template and your suggestion got me thinking about what I was actually looking for. A little kint() action, and I got what I needed:
{{ file_url(item.content['#paragraph'].field_media_image.entity.field_media_image.entity.uri.value) }}TGIF!
Another oddball
Here's another example of some code I used to get fields from an Entity reference revisions selector field from within a paragraph.html.twig template:
{% for item in content.field_selector["#items"] %}{% set image = item.entity.field_media_image.entity.field_media_image %}
{% if image.entity.uri.value != "" %}<img src="{{ file_url(image.entity.uri.value) }}" alt="={{ image.alt }}" />
{% else %}
<img src="/assets/images/hero-inner.jpg" alt="Students listening intently" />
{% endif %}
{{ item.entity.field_caption_title.0.value }}{{ item.entity.field_caption_text.0.value|raw }}
{% endfor %}
Hope this helps someone (or my future self).
still valid
Hi Robert, thanks for sharing your solution. I've just tried it and i can't make it work:
- I am within a (renamed) field.html.twig template
- The field is within a paragraf section
- The name of the field is field_sectionimage_img
and i want to get the uri of a media image.
So i've tried various versions of your solution without success:
do you have any hint how i can get the value?
got it
found it myself: the trick is not to go into the field template but rather stay on the paragraf template level. there i can access all values...