Don't use picture tag when there's only 1 source tag

Created on 14 November 2024, 4 months ago

Problem/Motivation

The responsive image module is designed to usually output a picture element. Except when (from template_preprocess_responsive_image()):

// There is only one source tag with an empty media attribute. This means
// we can output an image tag with the srcset attribute instead of a
// picture tag.
$variables['output_image_tag'] = TRUE;

The webp module will duplicate any source tag that is not already a webp image and then prepend those new sources to the sources list and force the responsive image module to use the picture element since there will always be 2 or more sources.

Smartly, if a source in a responsive image style is already converted to webp (with Drupal Core's "Convert" image filter), then webp will skip that source and only duplicate sources that are not webp.

However, there is a bug in webp module if there is only one source in the responsive image style and its already a webp image because the webp module won't actually add any additional source tags, but the webp module will still turn off the output_image_tag twig variable.

The webp module's code comment is wrong here:

// Never output a single image tag, because
// we will always have at least two sources.

because you won't have two sources if there is only one original source and it's already a webp image.

Under these specific circumstances, the webp module will force the responsive image template to use a picture element when it shouldn't.

Steps to reproduce

  1. Configure 1 or more image styles to use Drupal Core's "Convert" image with the "webp" image type chosen.
  2. Create a new responsive image style
    1. For the , choose "Responsive image".
    2. That breakpoint group only contains a single breakpoint, "Viewport Sizing". For that breakpoint's , choose "Select multiple image styles and use the sizes attribute."
    3. Only pick image styles from step 1.
  3. Configure an image field to use that responsive image style.
  4. Look at the rendered markup. It incorrectly uses the picture element and only contains 1 source element.
  5. If you disable the webp module (or apply this issue's fix), you'll see that same rendered markup no longer using the picture element, but instead using a img element with srcset and sizes attributes.

Proposed resolution

Check if webp actually needs to add sources to the list before setting the output_image_tag variable.

🐛 Bug report
Status

Active

Version

1.0

Component

Code

Created by

🇹🇼Taiwan johnalbin Taipei, Taiwan

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024