srcset and sizes in Kirby image tag
Just in case anybody is dealing with srcset and sizes in a Kirby image tag: I’ll show you all the bits and pieces I’ve ended up with. With thanks to @sebastiangreger.
plugins/image/index:
<?php
$originalTag = Kirby\Text\KirbyTag::$types['image'];
Kirby::plugin('your/image', [
'tags' => [
'image' => [
'attr' => array_merge(
$originalTag['attr'],
[
'srcset',
'sizes'
]),
'html' => function($tag) use ($originalTag) {
$file = $tag->file($tag->value());
$srcset = $tag->srcset;
$srcset = option('thumbs.srcsets.' . $tag->srcset );
$sizes = option('srcset-sizes.' . $tag->sizes );
$result = $originalTag['html']($tag);
if (! $file === true || is_null($srcset) === true || is_null($sizes) === true) {
return $result;
}
$pattern = '/<img.*?>/i';
// src image with sizes and quality (if any) in filename
$src = $file->thumb('large')->url();
// build a new image tag with the srcset and sizes
$image = Html::img($src, [
'width' => $tag->width,
'height' => $tag->height,
'class' => $tag->imgclass,
'title' => $tag->title,
'alt' => $tag->alt ?? ' ',
'srcset' => $file->srcset($srcset),
'sizes' => $sizes
]);
// replace the old image tag
$result = preg_replace($pattern, $image , $result);
return $result;
}
]
]
]);
site/config/config (to be specified: different srcsets and sizes for smaller images in columns for example, the srcset and sizes underneath are just a quick example, use your own)
'thumbs' => [
'presets' => [
'small' => ['width' => 400, 'quality' => 75],
'normal' => ['width' => 800, 'quality' => 75],
'large' => ['width' => 1200, 'quality' => 75], // for use in src
'xlarge' => ['width' => 1600, 'quality' => 75]
]
'srcsets' => [
'default' => [
'400w' => ['width' => 400, 'quality' => 75],
'800w' => ['width' => 800, 'quality' => 75],
'1200w' => ['width' => 1200, 'quality' => 75],
'1600w' => ['width' => 1600, 'quality' => 75]
]
'columns' => [ ],
],
],
'srcset-sizes' => [
'default' => '(max-width: 500px) 400px, (max-width: 800px) 800px',
'columns' => ' ',
],
Kirby image tag (both srcset and sizes should be specified):
(image:my-image.jpg srcset:default sizes:default)
Result (corresponding filenames for src and srcset and sizes):
<img alt="Image alt text here"
sizes="(max-width: 500px) 400px, (max-width: 799px) 800px"
src="http://…/media/…/my-image-1200x-q75.jpg"
srcset="http://…/media/…/my-image-400x-q75.jpg 400w,
http://…/media/…/my-image-800x-q75.jpg 800w,
http://…/media/…/my-image-1200x-q75.jpg 1200w,
http://…/media/…/my-image-1600x-q75.jpg 1600w
">