Skip to content

Instantly share code, notes, and snippets.

@foobartel
Last active August 15, 2021 08:54
Show Gist options
  • Save foobartel/9cd81f653111f94bf3982f5bddaddb1d to your computer and use it in GitHub Desktop.
Save foobartel/9cd81f653111f94bf3982f5bddaddb1d to your computer and use it in GitHub Desktop.
Kirby 3 Image Block with support for webp, avif and native lazy loading
This block requires Kirby 3.6 or later
- Place image.php in /site/snippets/blocks/image.php
- Place image.yml in /site/blueprints/blocks/image.yml
- Add the thumbs driver to the return statement in /site/config/config.php
# Add to Kirby configuration
# avif image format currently only works with the ImageMagick driver
return [
'thumbs' => [
'driver' => 'im',
],
]
<?php
/** @var \Kirby\Cms\Block $block */
$alt = $block->alt();
$caption = $block->caption();
$crop = $block->crop()->isTrue();
$link = $block->link();
$lazy = $block->lazy()->bool();
$ratio = $block->ratio()->or('auto');
$src = null;
if ($block->location() == 'web') {
$src = $block->src()->esc();
} elseif ($image = $block->image()->toFile()) {
$alt = $alt ?? $image->alt();
$src = $image->url();
}
if( $lazy ) {
$lazy = 'loading="lazy" ';
}
?>
<?php if ($src): ?>
<figure<?= attr(['data-ratio' => $ratio, 'data-crop' => $crop], ' ') ?>>
<?php if ($link->isNotEmpty()): ?>
<a href="<?= esc($link->toUrl()) ?>">
<picture>
<source srcset="<?= $image->thumb(['width' => 1200, 'format' => 'avif', 'quality' => 60 ])->url() ?>" type="image/avif">
<source srcset="<?= $image->thumb(['width' => 1200, 'format' => 'webp', 'quality' => 60])->url() ?>" type="image/webp">
<img src="<?= $image->thumb(['width' => 1200, 'quality' => 60 ])->url() ?>" alt="<?= $alt->esc() ?>" <?= $lazy ?>>
</picture>
</a>
<?php else: ?>
<picture>
<source srcset="<?= $image->thumb(['width' => 1200, 'format' => 'avif', 'quality' => 60 ])->url() ?>" type="image/avif">
<source srcset="<?= $image->thumb(['width' => 1200, 'format' => 'webp', 'quality' => 60])->url() ?>" type="image/webp">
<img src="<?= $image->thumb(['width' => 1200, 'quality' => 60 ])->url() ?>" alt="<?= $alt->esc() ?>" <?= $lazy ?>>
</picture>
<?php endif ?>
<?php if ($caption->isNotEmpty()): ?>
<figcaption>
<?= $caption ?>
</figcaption>
<?php endif ?>
</figure>
<?php endif ?>
name: Image
icon: image
fields:
image:
type: files
multiple: false
width: 1/2
lazy:
type: toggle
icon: title
width: 1/2
alt:
type: text
icon: title
caption:
type: writer
inline: true
icon: text
link:
type: text
icon: url
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment