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.

2 Answers 2


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


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

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.