index-shop/site/snippets/picture.php

57 lines
1.8 KiB
PHP
Raw Permalink Normal View History

<?php
/**
* Picture Snippet - Optimized image output with responsive srcset and WebP support
*
* @param Kirby\Cms\File $file - Required: The image file object
* @param string $alt - Optional: Alt text (defaults to file's alt field)
* @param string $class - Optional: CSS class for the picture element
* @param string|int $size - Optional: Size hint in vw for the sizes attribute (e.g., 50 for 50vw)
* @param bool $lazy - Optional: Enable native lazy loading (default: true)
* @param string $preset - Optional: Thumb preset to use (default: 'default')
* @param bool $crop - Optional: Crop the image (default: false)
*/
if (!isset($file) || !$file) return;
// Configuration
$alt = $alt ?? $file->alt()->or($file->filename())->value();
$class = isset($class) ? 'class="' . $class . '"' : '';
$lazy = $lazy ?? true;
$preset = $preset ?? 'default';
// Sizes attribute - determines which image size the browser should load
if (isset($size)) {
$sizes = is_numeric($size)
? "(min-width: 1024px) {$size}vw, 100vw"
: $size;
} else {
$sizes = "(min-width: 1024px) 50vw, 100vw";
}
// Generate srcsets for WebP and fallback
$webpSrcset = $file->srcset('webp');
$srcset = $file->srcset('default');
// Get optimized source URL
$src = $file->thumb($preset)->url();
// Get dimensions to avoid layout shift
$width = $file->width();
$height = $file->height();
$aspectRatio = $height > 0 ? ($height / $width) * 100 : 0;
?>
<picture <?= $class ?> data-id="<?= $file->uuid() ?>">
<source srcset="<?= $webpSrcset ?>" sizes="<?= $sizes ?>" type="image/webp">
<img
src="<?= $src ?>"
srcset="<?= $srcset ?>"
sizes="<?= $sizes ?>"
width="<?= $width ?>"
height="<?= $height ?>"
alt="<?= $alt ?>"
<?= $lazy ? 'loading="lazy"' : '' ?>
style="aspect-ratio: <?= $width ?> / <?= $height ?>;"
>
</picture>