index-shop/site/snippets/picture.php
isUnknown 30d09d6104 Add responsive image optimization with WebP support
- Configure thumbs presets in config.php (quality 85%, WebP format)
- Create picture snippet with srcset and WebP support
- Add product-card and product-detail presets
- Update templates to use optimized images
- Implement native lazy loading for product cards
- Add aspect-ratio CSS for layout stability

Improvements over reference project:
- Complete PHPDoc documentation
- Native CSS aspect-ratio support
- Optimized lazy loading strategy
- Product-specific image presets

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-10 16:00:58 +01:00

56 lines
1.8 KiB
PHP

<?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>