51 lines
1.8 KiB
PHP
51 lines
1.8 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
/**
|
|
* Responsives Bild aus Varianten-Set ODER Einzeldatei. Props:
|
|
* $image array{base: string, widths: int[], alt: string} — Varianten <base>-<w>.jpg
|
|
* ODER array{src: string, width: int, height: int, alt: string} — Originaldatei 1:1
|
|
* $sizes string (optional, default '100vw')
|
|
* $eager bool (optional) — above the fold: eager + fetchpriority high
|
|
* $class string (optional)
|
|
*/
|
|
$sizes = $sizes ?? '100vw';
|
|
$eager = $eager ?? false;
|
|
$class = $class ?? '';
|
|
|
|
if (!empty($image['src'])): ?>
|
|
<img<?= $class !== '' ? ' class="' . e($class) . '"' : '' ?>
|
|
src="<?= e(asset($image['src'])) ?>"
|
|
alt="<?= e($image['alt']) ?>"
|
|
width="<?= e($image['width']) ?>" height="<?= e($image['height']) ?>"
|
|
<?= $eager ? 'loading="eager" fetchpriority="high"' : 'loading="lazy" decoding="async"' ?>>
|
|
<?php return; endif;
|
|
|
|
$widths = $image['widths'];
|
|
$largest = max($widths);
|
|
$srcset = implode(', ', array_map(
|
|
static fn (int $w): string => asset("{$image['base']}-{$w}.jpg") . " {$w}w",
|
|
$widths
|
|
));
|
|
|
|
// Maße der größten Variante für width/height (CLS-Vermeidung).
|
|
[$w, $h] = (function () use ($image, $largest): array {
|
|
static $dims = [];
|
|
$file = PUBLIC_PATH . "/assets/{$image['base']}-{$largest}.jpg";
|
|
$key = $file;
|
|
if (!isset($dims[$key])) {
|
|
$size = is_file($file) ? (getimagesize($file) ?: [0, 0]) : [0, 0];
|
|
$dims[$key] = [$size[0], $size[1]];
|
|
}
|
|
return $dims[$key];
|
|
})();
|
|
?>
|
|
<img<?= $class !== '' ? ' class="' . e($class) . '"' : '' ?>
|
|
src="<?= e(asset("{$image['base']}-{$largest}.jpg")) ?>"
|
|
srcset="<?= e($srcset) ?>"
|
|
sizes="<?= e($sizes) ?>"
|
|
alt="<?= e($image['alt']) ?>"
|
|
width="<?= e($w) ?>" height="<?= e($h) ?>"
|
|
<?= $eager ? 'loading="eager" fetchpriority="high"' : 'loading="lazy" decoding="async"' ?>>
|