You are here

function template_preprocess_image in Drupal 8

Same name and namespace in other branches
  1. 9 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 798
The theme system, which controls the output of Drupal.

Code

function template_preprocess_image(&$variables) {
  if (!empty($variables['uri'])) {
    $variables['attributes']['src'] = file_url_transform_relative(file_create_url($variables['uri']));
  }

  // Generate a srcset attribute conforming to the spec at
  // http://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_transform_relative(file_create_url($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];
    }
  }
}