Skip to content

Instantly share code, notes, and snippets.

@mbecher
Last active August 1, 2019 11:33
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mbecher/0106039f494258728d52 to your computer and use it in GitHub Desktop.
Save mbecher/0106039f494258728d52 to your computer and use it in GitHub Desktop.
getkirby tags/figure.php with srcset and thumbnail creation
<?php
kirbytext::$tags['figure'] = array(
'attr' => array(
'width',
'height',
'alt',
'text',
'title',
'class',
'imgclass',
'linkclass',
'caption',
'link',
'target',
'popup',
'rel'
),
'html' => function($tag) {
$url = $tag->attr('figure');
$alt = $tag->attr('alt');
$title = $tag->attr('title');
$link = $tag->attr('link');
$caption = $tag->attr('caption');
$file = $tag->file($url);
// use the file url if available and otherwise the given url
$url = $file ? $file->url() : url($url);
// thumbs
$width = $tag->attr('width') ? $tag->attr('width') : '800';
$url = thumb($file, array('width' => $width, 'crop' => false, 'quality' => 85))->url();
$url2x = thumb($file, array('width' => $width*2, 'crop' => false, 'quality' => 85))->url();
$url3x = thumb($file, array('width' => $width*3, 'crop' => false, 'quality' => 85))->url();
// srcset images
$img = explode('.', basename($url));
$path = dirname($url). '/';
$srcset = $url . ' 1x' . ', ';
$srcset .= $url2x . ' 2x' . ', ';
$srcset .= $url3x . ' 3x';
// alt is just an alternative for text
if($text = $tag->attr('text')) $alt = $text;
// try to get the title from the image object and use it as alt text
if($file) {
if(empty($alt) and $file->alt() != '') {
$alt = $file->alt();
}
if(empty($title) and $file->title() != '') {
$title = $file->title();
}
}
if(empty($alt)) $alt = pathinfo($url, PATHINFO_FILENAME);
$image = html::img($url, array(
'srcset' => html($srcset),
'width' => $tag->attr('width'),
'height' => thumb($file, array('width' => $width, 'crop' => false, 'quality' => 85))->height(),
'class' => $tag->attr('imgclass'),
'title' => html($title),
'alt' => html($alt)
));
if($tag->attr('link')) {
// build the href for the link
if($link == 'self') {
$href = $url;
} else if($file and $link == $file->filename()) {
$href = $file->url();
} else {
$href = $link;
}
$image = html::a(url($href), $image, array(
'rel' => $tag->attr('rel'),
'class' => $tag->attr('linkclass'),
'title' => html($tag->attr('title')),
'target' => $tag->target()
));
}
$figure = new Brick('figure');
$figure->addClass($tag->attr('class'));
$figure->append($image);
if(!empty($caption)) {
$figure->append('<figcaption>' . html($caption) . '</figcaption>');
}
return $figure;
}
);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment