Creating a controller for /site/snippets/header.php

Hello All

I have a /site/snippets/header.php file that I include in pretty much all of my templates. Within this file, I also include site/snippets/menu.php. Is it possible to create functions for header.php in the site/controller folder or anywhere else?

Thanks!

For each project I work with in Kirby, I like to create a helpers.php (or site-name.php, however you like) in site/plugins. This will get auto-loaded on every request, and any functions defined therein will be available in all scopes.

Typically, I’ll use a class with a number of static methods, like this:

<? class AWM {
  public static function body_classes ($additional) {
    $classes = [
      page()->intendedTemplate(),
      page()->uid()
    ]
    array_push($classes, $additional);
    return join(array_unique($classes), ' ');
  }
}

…which makes them accessible, like many of the Kirby Toolkit functions.

While this isn’t exactly the perfect “snippet controller” you’re looking for, I think it allows you to do many of the same things as you’re hoping.

This class could also have static properties, which could store whatever you like. I personally like the function return values, because it mimics the Kirby style.

5 Likes

This is what I would do as well. Does not necessarily have to be a class, but of course that’s even cleaner.

Great! I’ve been looking for a decent way to incorporate some custom code for a project, shared between different pages and this feels like the way to go. Thanks for sharing.