0

I have a custom block type that has a media entity field that is an image. I want to extract that image url and set it as a div background image in the html.twig file, but I can't get it to work. The twig file is block--inline-block--hero-w-title.html.twig If I do

{{ content.field_hero_image[0] }}

it will display the rendered image with all the divs and stuff, but I can't figure out how to get the image url from content.field_hero_image. I have googled it in every way I can think of, and tried everything I have seen but can't figure out why nothing is working.

Do any of y'all know how to get the image url from media entity content.field_hero_image?

I have tried the listed and more so far:

content.field_hero_image|file_uri (twig_tweak. Failed due to sending an array when it was expecting object?) 
content.field_hero_image|file_url (twig_tweak: returned null) 
content.field_hero_image.entity.field_media_image.entity.uri.value (returned null) 
content.field_hero_image.entity.uri.value (returned null)
1
  • Are you sure you've put the media to be displayed in the block's display settings? Which field formatter? Is the media entity's display settings configured correctly as well? Which field formatter?
    – leymannx
    Jul 11, 2023 at 6:35

1 Answer 1

1

The last lines look very promising for an image field nested in a media entity, you only have to start with the block content entity:

{{ elements.content['#block_content'].field_hero_image.entity.field_media_image.entity.uri.value }}

In a standard entity template, you would start with the name of the entity like {{ node. or {{ paragraph.. The block content entity doesn't have an entity template and in the block plugin template you need to look in the render element build array elements for the entity object.

Then use file_url() to transform the URI to a URL.

0

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.