Using Webp Plugin in Core Image Block


we have a custom block to output images to kirby using the webp plugin from hash and salt by @jimbobrjames. with the new kirby version we would like to use the core image block. But what we are missing here is the conversion to webp.
can someone help us how to get the webp functionality of the plugin into the image block? Thanks a lot!

The plugin has some methods that convert to/fetch the webp variant of an image. You can use those in your custom image block snippet.

You can use the snippet built into the plug-in for this. Use it in a for each loop and replace the source attribute with the $var of your image and the snippet will do the work for you. It checks if the jpeg has a matching webp version and converts on the fly if its missing. The type attritubute sets wether the fallback image is a Jpeg or PNG image so you may need a bit of logic there to check what the file type of the image set in the block. A ternary should do it i think.

Something like this…

<?php foreach ($blockimages as $blockimage): ?>
    <?php snippet('webp', ['sizes' => [1920, 1140, 768], 'src' => $blockimage, 'type' => 'jpg', 'class' => 'your-class', 'width' => 920, 'height' => 720]); ?>
<?php endforeach; ?>

thanks for your help! this actually works! :slight_smile:
it is possible to define the alt-tag for an image within the core image block.
could you image why the $alt variable is not passed thru to the webp plugin?
you write in your documentation of the plugin, that it willl also accept a parameter for ‘alt’.
so i wrote it in the snippet, but there is no output of an alt-tag.
could you help? thanks!

I think the alt field in the block blueprint probably has a different name to the one in the snippet. You probably just need to match those up to get it working. The snippet is meant to get the alt tag from the files meta file, not from the the block blueprint.

i tried the following:

<?php foreach ($data->image()->toFiles() as $image) : ?>
        <?php snippet('webp', ['sizes' => [1920, 1140, 640, 320], 'src' => $image, 'alt' => $alt, 'type' => 'png', 'class' => 'image hov-grow', 'width' => 1920, 'height' => 1920]); ?>
<?php endforeach; ?>

the variable is defined like this:
$alt = $alt ?? $image->alt();