Score:0

How to render a media field as responsive image?

cn flag

I'm trying to render a media field as a responsive image in a custom twig template.

My naive approach looks like this:

{% include 'responsive-image.html.twig' with {
  "sources": content.field_media,
} %}

which simply yields a series of errors like this:

"0" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php). 

Presumably one of the reasons this fails is that I'm not providing a view mode, but I'm also not sure how to do so.

Score:0
cn flag

Since you are posting Twig code here a solution in Twig:

First get the image URIs. In this example starting with the node if this is a node template:

{% for media in node.field_slider_image  %}

  <img src="{{ file_url(media.entity.field_image.entity.uri.value) }}">

{% endfor %}

See Display image/media entities view from node to twig template.

If you want to display an image style don't call the image template directly. Build a render element for the image template. See Rendering an image field in page.html.twig with a custom image style

Score:0
de flag

This is how I would do it. Note that I defer as much as possible to configuration through the UI, to limit custom code that needs to be maintained.

  1. Use the Responsive Image module, set up your responsive image style (breakpoints etc).
  2. Create a new view mode for the media type, named Image Only.
  3. Navigate to the media type, 'Manage View' tab, and enable the new view mode.
  4. Edit the new view mode. Set all fields except the image to be hidden. Set the formatter for the view mode to use the responsive image style created in step 1.
  5. Render your media item using that view mode in the twig template. Note that the following link shows how to render the teaser view mode, you want to render the image_only view mode you created in step 2: https://drupal.stackexchange.com/a/207719/66659
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.