public static function Blazy::buildBreakpointAttributes in Blazy 8
Same name and namespace in other branches
- 7 src/Blazy.php \Drupal\blazy\Blazy::buildBreakpointAttributes()
Provides re-usable breakpoint data-attributes.
$settings['breakpoints'] must contain: xs, sm, md, lg breakpoints with the expected keys: width, image_style.
See also
1 call to Blazy::buildBreakpointAttributes()
- Blazy::buildImage in src/
Blazy.php - Modifies variables for regular image.
File
- src/
Blazy.php, line 270
Class
- Blazy
- Implements BlazyInterface.
Namespace
Drupal\blazyCode
public static function buildBreakpointAttributes(array &$attributes = [], array &$settings = []) {
// Defines attributes, builtin, or supported lazyload such as Slick.
$attributes['class'][] = $settings['lazy_class'];
$attributes['data-' . $settings['lazy_attribute']] = $settings['image_url'];
// Only provide multi-serving image URLs if breakpoints are provided.
if (empty($settings['breakpoints'])) {
return;
}
$srcset = $json = [];
foreach ($settings['breakpoints'] as $key => $breakpoint) {
if (empty($breakpoint['image_style']) || empty($breakpoint['width'])) {
continue;
}
if ($style = ImageStyle::load($breakpoint['image_style'])) {
$url = file_url_transform_relative($style
->buildUrl($settings['uri']));
// Supports multi-breakpoint aspect ratio with irregular sizes.
// Yet, only provide individual dimensions if not already set.
// @see Drupal\blazy\BlazyManager::setDimensionsOnce().
if (!empty($settings['_breakpoint_ratio']) && empty($settings['blazy_data']['dimensions'])) {
$dimensions = [
'width' => $settings['width'],
'height' => $settings['height'],
];
$style
->transformDimensions($dimensions, $settings['uri']);
if ($width = self::widthFromDescriptors($breakpoint['width'])) {
$json[$width] = round($dimensions['height'] / $dimensions['width'] * 100, 2);
}
}
$settings['breakpoints'][$key]['url'] = $url;
// @todo: Recheck library if multi-styled BG is still supported anyway.
// Confirmed: still working with GridStack multi-image-style per item.
if (!empty($settings['background'])) {
$attributes['data-src-' . $key] = $url;
}
elseif (!empty($breakpoint['width'])) {
$width = trim($breakpoint['width']);
$width = is_numeric($width) ? $width . 'w' : $width;
$srcset[] = $url . ' ' . $width;
}
}
}
if ($srcset) {
$settings['srcset'] = implode(', ', $srcset);
$attributes['srcset'] = '';
$attributes['data-srcset'] = $settings['srcset'];
$attributes['sizes'] = '100w';
if (!empty($settings['sizes'])) {
$attributes['sizes'] = trim($settings['sizes']);
unset($attributes['height'], $attributes['width']);
}
}
if ($json) {
$settings['blazy_data']['dimensions'] = $json;
}
}