In the example, yes. I guess the article was published before Mastodon started becoming somewhat mainstream, and getting 3 or 4 requests wasn’t a problem.
This is how I would approach it if the generation actually causes performance issues:
site/config/config.php
<?php
use Kirby\Cms\Page;
return [
/** ... the usual stuff here */
'hooks' => [
'page.update:after' => function (Page $newPage) {
// if the page has a createOgImage() method, call it.
if(method_exists($newPage, 'createOgImage') {
$newPage->createOgImage();
}
}
]
];
site/models/article.php
<?php
use Kirby\Cms\Page;
class ArticlePage extends Page {
/**
* Generate the OpenGraph image
*/
public function createOgImage() {
$canvas = imagecreatetruecolor(1200, 628);
// @TODO: draw stuff here
// save file
imagepng($canvas, $this->root() . '/ogimage.png');
// reset the internal cache so that kirby picks up the new file
$this->purge();
}
/**
* Generate the OpenGraph image if it doesn't exist
* Return a File object for it
*/
public function ogImage() {
if($this->file('ogimage.png') === null)) {
$this->createOgImage();
}
return $this->file('ogimage.png');
}
}
in the template:
<meta
property="og:image"
content="<?= $page->ogImage()?->url() ?? url('opengraph.png') ?>"
>
Docs: