Grav CMS
In November 2026 I decided to move from Backdrop to Grav CMS mainly because keeping Backdrop updated had become a bit of a problem, despite using Bee and Ansible.
I had lost some pages probably die to a database problem, so Grav CMS seemed to suit with no database, just a flat file layout.
Images on pages not regenerating
Several pages on my site have images of graphs etc updated every 5 mins. These are not updating due to browser caching. With Backdrop and much to my surprise Grav both had this problem. Despite adding the Token Plugin to Backdrop and disabling the cahce on the relevant pages in Grav I still had the problem, so to update the page I had to press Shift-Ctrl-R to do a hard refresh. I finally found a solution by asking "Claude" AI. Here is his solution which seems to work:
Claude's Solution
By adding a php method to add the timestamp query to all local images across the site which is fired in the getSubscribedEvents() method: So I added the following line to the getSubscribedEvents() method in the theme php file:
'onOutputGenerated' => ['onOutputGenerated', 0],
Then the onOutputGenerated method is as follows:
/** Adds ?v=<file modified time> to local image addresses so browsers reload changed images. */
public function onOutputGenerated(): void
{
$base = rtrim($this->grav['base_url_relative'], '/');
$root = rtrim(GRAV_ROOT, '/');
$this->grav->output = preg_replace_callback(
'/\b(src|href)=(["\'])([^"\'?#]+\.(?:png|jpe?g|gif|webp|svg))\2/i',
function (array $m) use ($base, $root) {
$url = $m[3];
// Local addresses only: skip http(s):, //host and data: URLs.
if (!str_starts_with($url, '/') || str_starts_with($url, '//')) {
return $m[0];
}
if ($base !== '' && !str_starts_with($url, $base . '/')) {
return $m[0];
}
$file = $root . rawurldecode(substr($url, strlen($base)));
$time = is_file($file) ? filemtime($file) : false;
return $time ? $m[1] . '=' . $m[2] . $url . '?v=' . $time . $m[2] : $m[0];
},
$this->grav->output
) ?? $this->grav->output;
}
Here is "Claude's" explanation: How it behaves:
- Local files only. Images on other sites are left alone, and so is any address that doesn't match a real file.
- Existing parameters. An address that already has a ? is skipped, so nothing gets a second version tag. That includes any image URLs where you've already added ?v= in the PHP classes.
- Link targets. It applies to src and href, so the links on your thumbnails also get the tag.
- Relative addresses. An address without a leading / (for example images/x.jpg) is not changed. Grav normally writes absolute ones for content images, but check one in the page source if an image still looks stale.
More time to be sure, but I think it works.