Add Lightbox to KirbyText Image Tag

I’m looking to add a lightbox to the KirbyText Image Tag, the way that Images in Block Layouts have them added.

I was reviewing the following custom tag tutorial but the final part of replacing the HTML lost me and I’m unsure how to even debug or test.

https://getkirby.com/docs/cookbook/extensions/extending-kirbytags

Can anyone point me in the right direction of making this possible?

You don’t have to use the original tag but can simply overwrite it. Refer to the source code for guidance:

Thanks! I’d actually pulled up the tags.php code as you recommended it and it was helpful to see what was available.

This is what I ended up doing if anyone needs it. It requires that the lightbox Kirby comes with be installed.

<?php

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

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

                $file = $tag->file($tag->value());
                $result = $originalTag['html']($tag);

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

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

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

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

                return $result;
            }
        ]
    ]
]);
1 Like