function template_preprocess_image_style in Drupal 10
Same name and namespace in other branches
- 8 core/modules/image/image.module \template_preprocess_image_style()
- 9 core/modules/image/image.module \template_preprocess_image_style()
Prepares variables for image style templates.
Default template: image-style.html.twig.
Parameters
array $variables: An associative array containing:
- width: The width of the image.
- height: The height of the image.
- style_name: The name of the image style to be applied.
- uri: URI of the source image before styling.
- alt: The alternative text for text-based browsers. HTML 4 and XHTML 1.0 always require an alt attribute. The HTML 5 draft allows the alt attribute to be omitted in some cases. Therefore, this variable defaults to an empty string, but can be set to NULL for the attribute to be omitted. Usually, neither omission nor an empty string satisfies accessibility requirements, so it is strongly encouraged for code using '#theme' => 'image_style' to pass a meaningful value for this variable.
- title: The title text is displayed when the image is hovered in some popular browsers.
- attributes: Associative array of additional attributes to be placed in the img tag.
File
- core/
modules/ image/ image.module, line 252 - Exposes global functionality for creating image styles.
Code
function template_preprocess_image_style(&$variables) {
$style = ImageStyle::load($variables['style_name']);
// Determine the dimensions of the styled image.
$dimensions = [
'width' => $variables['width'],
'height' => $variables['height'],
];
$style
->transformDimensions($dimensions, $variables['uri']);
$variables['image'] = [
'#theme' => 'image',
'#width' => $dimensions['width'],
'#height' => $dimensions['height'],
'#attributes' => $variables['attributes'],
'#style_name' => $variables['style_name'],
];
// If the current image toolkit supports this file type, prepare the URI for
// the derivative image. If not, just use the original image resized to the
// dimensions specified by the style.
if ($style
->supportsUri($variables['uri'])) {
$variables['image']['#uri'] = $style
->buildUrl($variables['uri']);
}
else {
$variables['image']['#uri'] = $variables['uri'];
// Don't render the image by default, but allow other preprocess functions
// to override that if they need to.
$variables['image']['#access'] = FALSE;
// Inform the site builders why their image didn't work.
\Drupal::logger('image')
->warning('Could not apply @style image style to @uri because the style does not support it.', [
'@style' => $style
->label(),
'@uri' => $variables['uri'],
]);
}
if (isset($variables['alt']) || array_key_exists('alt', $variables)) {
$variables['image']['#alt'] = $variables['alt'];
}
if (isset($variables['title']) || array_key_exists('title', $variables)) {
$variables['image']['#title'] = $variables['title'];
}
}