1

There is a field_image (image) field on the basic content type. Using the Responsive Image, we enabled it on the Default view mode for the field_image field using a Responsive Image style.

The reason why we are setting the Image url as the data-src attribute is because we are using Lazysizes javascript library to lazyload the images. The Responsive Image module outputs using source srcset as separate tags from the img tag.

In my testing, I have found that although the browser fetches whatever size it needs to based on the Responsive Image style configuration, it does not change the image url.

How would we control the output of the image so that we can get the image to display similar to below?

Goal:

  1. Lazy load images even while using Responsive Image Module
  2. Output the image field so that the data-src is set, src is not set, and the "lazyload" class is added

Current situation:

<picture>
<source srcset="/image.jpg 1x" media="all and (min-width: 768px)" type="image/jpeg">
<source srcset="/image2.jpg 1x" media="all and (min-width: 320px)" type="image/jpeg">
<img src="/original-image" alt="alt_text" >
</picture>

Desired Output:

<picture>
<source srcset="/image.jpg 1x" media="all and (min-width: 768px)" type="image/jpeg">
<source srcset="/image2.jpg 1x" media="all and (min-width: 320px)" type="image/jpeg">
<img src="/original-image" alt="alt_text" class="lazyload">
</picture>

1 Answer 1

1

The responsive image module creates these with a twig template called: responsive-image.html.twig.

You have two options to change the output. You can either copy this template from it's location under core/modules/responsive_image/templates to your theme.

Or you can use the hook_preprocess_responsive_image() in a module or your my_theme.theme file.

Basically, you will need to change the values in the source_attributes object. E.g. grab the value of the src attributes, delete it, and add your srcset attribute with the value of the src attribute.

1
  • wow i didn't even notice that responsive-image.html.twig existed. I was able to use that twig template to get what i need. Dec 12, 2017 at 18:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.