Accessing new srcset via Kirbytext

Thank you so much for stepping through all the various corrections to this to make it work!

Now I can either enter (image: filename.jpg srcset: 800, 1200, 1600) or fallback to my config settings with just (image: filename.jpg) and both are generating the correct files that map to correct html attrs.

Here is the revised custom plugin based on your inputs for anyone who might find it useful:

<?php

$originalTag = Kirby\Text\KirbyTag::$types['image'];
Kirby::plugin('your/plugin', [
    'tags' => [
        'image' => [
            'attr' => array_merge(
                $originalTag['attr'],
                [
                    'srcset'
                ]),

            'html' => function($tag) use ($originalTag)  {

                $file = $tag->file($tag->value());

                // gets srcset array from config
                $presets = option('thumbs.srcsets.default');

                // sets srcset as kirbytag array with fallback to config array
                $srcset = $tag->srcset ? explode(',', $tag->srcset): $presets;
                
                // casts kirbytext array strings to ints
                $srcset = array_map(function($item) {
                    return (int) $item;
                }, $srcset);

                $result = $originalTag['html']($tag);

                if (! $file === true || is_null($srcset) === true) {
                    return $result;
                }

                $pattern = '/<img.*?>/i';

            // build a new image tag with the srcset
            $image = Html::img($tag->src, [
                'width' => $tag->width,
                'height' => $tag->height,
                'class' => $tag->imgclass,
                'title' => $tag->title,
                'alt' => $tag->alt ?? ' ',
                'srcset' => $file->srcset($srcset),
            ]);

            // replace the old image tag
            $result = preg_replace($pattern, $image , $result);

            return $result;
            }
        ]
    ]
]);

The presets in config/config.php look like this:

'thumbs' => [
    'srcsets' => [
      'default' => [ {your presets here} ],
    ],
  ],

I’m so pleased to have this solution, and be able to get started importing responsive images into my project. Thanks again.

1 Like