I wanted to have both the Kirby (image:)
tag work with relative urls but also the native ![Alt](image.jpg)
. It did not work out of the box so I built it.
When it’s useful
I’m trying a new approach to content writing. Instead of writing in the Panel where I get logged out a lot, I’ve started to write in Vscode. It has a great markdown preview and it’s possible to set a custom css for it.
It has support for native markdown code, but not for Kirby text tags, so the Kirby (image:
will not work for example, but the relative ![Alt][image.jpg]
does.
So no matter where the content came from, a markdown document or the Panel, it should work.
Content example
Without this solution only the first one will work. With this solution both works.
Kirby image tag:
(image: bear-2439923_1920.jpg)
Markdown image code:
![Test](bear-2439923_1920.jpg)
Solution
Config
Place in config.php
:
c::set('thumbs.presets', [
'content' => ['width' => 480, 'height' => 320, 'quality' => 30],
]);
I think the images should be resized so I implemented that as well. Put the code below inside a plugin:
field::$methods['kirbytext'] = field::$methods['kt'] = function($field) {
$field->value = relativeMarkdownLinks($field, $field->page->root(), $field->page->contentUrl());
$field->value = kirbytext($field->value);
return $field;
};
function relativeMarkdownLinks($field, $path, $url) {
return preg_replace_callback('/\[(.*?)\]\((.*?)\)/', function($matches) use ($field, $path, $url) {
$extension = pathinfo($matches[2], PATHINFO_EXTENSION);
if(!in_array($extension, ['jpg', 'jpeg', 'png', 'gif'])) return $matches[0];
$image = $field->page()->file($matches[2]);
$thumb = thumb($image, 'content');
$output = '[' . $matches[1] . '](' . $thumb->url() . ')';
return $output;
}, $field->value);
}
/*
Regex from:
https://stackoverflow.com/questions/24985530/parsing-a-markdown-style-link-safely
*/
Updated: Thanks @texnixe for a better solution for the thumb arg. Forgot to include a small function in the last version, but this version should work out of the box.