function template_preprocess_image

Same name in other branches
  1. 9 core/includes/theme.inc \template_preprocess_image()
  2. 8.9.x core/includes/theme.inc \template_preprocess_image()
  3. 10 core/includes/theme.inc \template_preprocess_image()

Prepares variables for image templates.

Default template: image.html.twig.

Parameters

array $variables: An associative array containing:

File

core/includes/theme.inc, line 624

Code

function template_preprocess_image(&$variables) {
    
    /** @var \Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator */
    $file_url_generator = \Drupal::service('file_url_generator');
    if (!empty($variables['uri'])) {
        $variables['attributes']['src'] = $file_url_generator->generateString($variables['uri']);
    }
    // Generate a srcset attribute conforming to the spec at
    // https://www.w3.org/html/wg/drafts/html/master/embedded-content.html#attr-img-srcset
    if (!empty($variables['srcset'])) {
        $srcset = [];
        foreach ($variables['srcset'] as $src) {
            // URI is mandatory.
            $source = $file_url_generator->generateString($src['uri']);
            if (isset($src['width']) && !empty($src['width'])) {
                $source .= ' ' . $src['width'];
            }
            elseif (isset($src['multiplier']) && !empty($src['multiplier'])) {
                $source .= ' ' . $src['multiplier'];
            }
            $srcset[] = $source;
        }
        $variables['attributes']['srcset'] = implode(', ', $srcset);
    }
    foreach ([
        'width',
        'height',
        'alt',
        'title',
        'sizes',
    ] as $key) {
        if (isset($variables[$key])) {
            // If the property has already been defined in the attributes,
            // do not override, including NULL.
            if (AttributeHelper::attributeExists($key, $variables['attributes'])) {
                continue;
            }
            $variables['attributes'][$key] = $variables[$key];
        }
    }
    // Without dimensions specified, layout shifts can occur,
    // which are more noticeable on pages that take some time to load.
    // As a result, only mark images as lazy load that have dimensions.
    if (isset($variables['width'], $variables['height']) && !isset($variables['attributes']['loading'])) {
        $variables['attributes']['loading'] = 'lazy';
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.