- Use a controller for the logic of your templates.
- A controller must have the same file name as the corresponding template file.
- Save controllers in
Controllers go into
/site/controllers. Create the directory if it's not there yet. Controllers are named exactly like the templates they belong to:
Kirby will automatically load the controller for your template if it can find one.
You can also have a default page controller: It works like a normal page controller. You only have to add it as
/site/controllers/site.php. Be aware that the default controller only works as a fallback if no specific page controller for the template exists. It is not loaded in addition to the template-specific one.
The basic code for a controller is very simple. It's an anonymous function that should return the variables that you want to pass to the template as an associative array.
In this case the
$bar variables will be available in the corresponding template.
A typical example where a controller can come in handy is a blog template. Fetching the right articles can take a couple lines of code and it's much nicer to wrap these in a controller. So let's create
The controller will take care of fetching the right articles and add pagination to them. It will then pass the
$pagination variables to the template to keep it clean.
With such a controller, the template can be super clean. A foreach loop for the articles and the prev/next pagination and you're done.
If you work with additional routes and you want to access the arguments from the router in your controller, you can use Kirby's
route() method to access an array of router arguments.
When using the
$page->render() method to return a page in a route, you can send an array of additional data with it:
In the controller, you can load each variable that you passed to the
render() method in the route into the controller's anonymous function and then work with it.
The properties defined in the
$data array are exposed to templates as global variables, so in use cases where you do not need them in a controller, you can use them directly.