Page models can be registered in a plugin or created in the
A page model definition is a PHP file with the same name as the template of the page you want to extend.
Kirby will automatically load the page model for your template if it can find one.
A page model is a PHP class that extends Kirby's default page class. The class name corresponds with the name of the template and text file. So if your text file is called
project.txt, Kirby will look for a
project.php model file with a
This page model will be loaded every time Kirby encounters a page of the given type (so project in this example), whether it is in a template, a snippet or anywhere else.
If your template name contains dashes or underscores, these have to be ignored when naming your page model class. That means, both
my_template.php will become:
The filenames of the model files themselves will keep the dash or underscore.
A page model can be used for example to fetch a cover image for a project page. Fetching the right image in the template or snippet can be a couple of lines of code. It is cleaner to seperate this functionality into a page model.
The page model will make a method called
cover() available for all your project pages. It will return the cover image, so you don't have to fetch it in the template code.
Note, that we use
$this where we would usually use
$page elsewhere in Kirby, because we refer to the extended page class in this case.
With such a page model you can now use the new cover method throughout all templates, snippets and controllers:
By creating the model and the cover method you don't have to repeat this code in every single snippet and template in which you are dealing with projects. The cover method in this case is pretty short and simple, but imagine this with more complex queries for images or other data. As an additional benefit you can make changes that are reflected throughout all your templates and snippets in a single file.
It is also possible to override the functionality of Kirby's
Page class. Be careful with this as it is possible to change Kirby's behaviour in unwanted ways!
A simple unintrusive example is to sort all images differently by default.
parent::images() in this example, we can refer to the original image method in Kirby's default
Page class in order to simply extend its functionality.
You can define page models in plugins to reuse them in other projects or to share them with the community. Learn more about page model plugins.