0

I have the following scenario:

I have a paragraph called Timeslot that contains an entity reference field to a content type called Class.

That content type has an image field called Class Badge.

I would like to print the Class Badge image inside this paragraph using a twig template.

1

I went in circles for hours before I found the solution. There are many posts with partial or theoretical solutions, but none of them worked for me.

My solution consists of a twig file, paragraph--timeslot.html.twig, which prints all of the fields from the Timeslot paragraph. The line which prints the Class Badge image looks like this:

<img src={{ file_url(paragraph.field_class.entity.field_class_badge.entity.uri.value) }} />

Working from right to left:

entity.uri.value is the uri value for the image field in the referenced node, which is the url prefaced by public:// or private://

entity.field_class_badge is the field in the referenced node that contains the image.

paragraph.field_class is the field in the paragraph that references the node.

file_url strips public:// or private:// from the uri that is retrieved so it can be used as the src in the image tag.

It is worth noting that uri is one of the database fields in the file_managed table. An alternative approach above could have been to use the filename field instead, and construct the URL manually within my code. Other fields that may prove useful would be filesize, created, and status.

Hopefully this helps someone. I doubt it's the definitive solution, but it worked for me.

UPDATE: I have since extended the solution above to display a specific image style, rather than the original image. Simply change the tag in the code to look like this, where class_badge is the machine name of the image style.

Essential - you'll need to install the Twig Tweaks module to get this version of the solution to work.

<img src={{ file_url(paragraph.field_monday_class.entity.field_class_badge.entity.uri.value | image_style('class_badge')) }}>
0

I ran into similar kind of problem, thought of posting my code here. My code is from the paragraph twig file

{% for item in paragraph.field_node_reference %}
<a href=" {{ path('entity.node.canonical', {'node': item.entity.id}) }} ">   
<img src={{ file_url(item.entity.entity.field_class_badge.entity.uri.value) }} />
</a>

{% endfor %}
0

In my opinion you need to at first get

  1. target_id from referenced field ($entity_id = $node->get('field_class')->getValue()['target_id'];)
  2. Load the entity ($entity = Node::load($entity_id)->toArray();)
  3. Then from that loaded entity extract your image field and pass to twig

No additional modules required.

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.