When using a responsive image with srcset the width and height attributes are not available in twig. Both of them are NULL When an image is uploaded that is too small images are stretched or blown up as described in this post: Responsive Images, The sizes Attribute, and Unexpected Image Sizes

Being able to set a with equal to the pixelsize of the image would solve this issue. How can I make these attributes available for twig?


This is not going to be easy due to Drupal's way of rendering images, you should not touch this unless you know how to write code. The code below is untested, but should give you a direction.

function THEMENAME_preprocess_responsive_image_formatter(array &$variables) {
  //this is the hook where you do get access to the image file entity
  //don't use 'width' as attribute name, it might get unset by Drupal in the following hook
  $variables['responsive_image']['#attributes']['data-original-image-width'] = $variables['item']->width;

function THEMENAME_preprocess_responsive_image(array &$variables) {
  //this is the preparing the rendering, here you can set the width attribute again
  $variables['#attributes']['width'] = $variables['img_element']['#attributes']['data-original-image-width'];

This is code just an outline, and most likely will only work if responsive images module is configured for an single img[srcset] and will not work with <picture> tags.

The hooks are quite good documented though, check the API docs for more information



  • The method does not seem to be defined: Error: Call to undefined method Drupal\image\Plugin\Field\FieldType\ImageItem::width() in mytheme_preprocess_responsive_image_formatter() (line 245 of themes/custom/hemet/mytheme.theme).
    – Benedikt
    Jan 22 '18 at 10:14
  • Remove the function call / parentheses from $variables['item']->width. it is a plain property. Updated the answer.
    – Hudri
    Jan 22 '18 at 10:26

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.