Snippets
Snippets are smaller blocks of code that you can reuse across templates. They are ideal for keeping your templates clean and maintainable.
Use cases
Typical examples in the Starterkit are the header.php
, footer.php
and menu.php
snippets that are used in every template.
Snippets are stored in the /site/snippets
folder and like templates, they have the extension .php
.
Make your life easier with snippets
A great way to clean up your templates and reuse parts of your templates multiple times.
Using snippets
Kirby's snippet()
helper function lets you include snippets into your templates:
Snippet | In your template |
---|---|
/site/snippets/header.php |
<?php snippet('header') ?> |
/site/snippets/menu.php |
<?php snippet('menu') ?> |
/site/snippets/footer.php |
<?php snippet('footer') ?> |
If you want to organize snippets in subfolders, you can do so. In that case, you have to pass the path to the snippet to the snippet function.
Snippet | In your template |
---|---|
/site/snippets/basics/header.php |
<?php snippet('basics/header') ?> |
Let's clean up a template
The most basic use case for snippets is splitting the header and footer into separate snippets. Let's explore how we can break up the basic template from the last section and make parts of it reusable:
The code above looks fine as long as we just have a single template. But with every template we add, we would have to repeat the same stuff over and over again. What if we wanted to make a change to the header or footer? We would have to touch every single file.
Well, we don't want to waste our precious time, so let's clean this up a bit!
Now that we have separated those parts, the final template looks very neat:
No matter how many more templates we will add to our site, the header and footer part are now only two lines of code. All we need to modify is the main part of the template.
Passing variables to snippets
Sometimes it is useful to pass a variable to a snippet.
With the above code, /site/snippets/mysnippet.php
will receive a title variable with the content "Hello!" that we can now echo in our snippet:
Snippet alternatives
Since 3.2.0
You can define an array of snippet alternatives if the first snippet cannot be found:
This is useful if you want to provide fallbacks for a snippet based on page input, in case the snippet does not exist:
Real life example: list of blog articles
The template
In this example, we pass the $article
variable (which is a page object) to the snippet and can then fetch the data from that page in our snippet:
The article.php
snippet
Assigning a snippet to a variable
The snippet()
function has a third, optional parameter of type boolean
. If set to true
, Kirby returns the parsed content instead of directly echoing it. With this option, snippets can be used in a variety of situations, not just inside page templates: