Creating a custom image tag

This is mine, for lazyload and use of srcset like you, maybe you can inspire from it :

<?php

Kirby::plugin('your/plugin', [
    'tags' => [
        'image' => [
            'attr' => [
                'alt',
                'caption',
                'class',
                'height',
                'imgclass',
                'link',
                'linkclass',
                'rel',
                'target',
                'title',
                'width'
            ],
            'html' => function($tag) {
                if ($tag->file = $tag->file($tag->value)) {

                    $tag->src     = $tag->file->url();
                    $tag->alt     = $tag->alt     ?? $tag->file->alt()->or(' ')->value();
                    $tag->title   = $tag->title   ?? $tag->file->title()->value();
                    $tag->caption = $tag->caption ?? $tag->file->caption()->value();
                    $tag->ratio   = $tag->file->ratio();
                        
                    $html = 
                    '<figure>
                        <div class="container" style="padding:0;background:rgb(250,250,250);position:relative;height: 0;display:block;padding-bottom:calc(100% / '. $tag->ratio .')">
                            <img class="lazyload" data-sizes="auto" data-srcset="' . $tag->file->srcset() . '" alt="' . $tag->alt . '">
                        </div>
                        <figcaption>'. kt($tag->caption) . '</figcaption>
                    </figure>';

                    $html = str_replace(array("\r", "\n"), '', $html);

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