Learn to build a lean & flexible blogging platform
Displaying a Post
Now that the list view is done, we need to craft the view that displays a single post.
We’ll call this page template “default.php”; Kirby will use this whenever it cannot find a template with the same name as the page file. This allows us to name our post files however we choose (instead of always having to name them “detail.txt” or the like).
Just as with the list view template, let’s start by filling in static content from our HTML template. Step-by-step, we’ll then replace each part with dynamic content.
We’re using a custom snippet for this job; but notice how we provide an array as the second parameter in the “snippet” function call. This allows us to supply variables to the snippet.
In this example, our code will make a variable available to the snippet that
is called $name and
has the author name as its value.
Inside the “author-bio.php” snippet, we can then easily access the passed parameter like this:
In this example, we’re using the simplest form of structure: lines prepended with a dash represent a list in YAML.
In fact, YAML can help to structure various kinds of data. You can read more about YAML on the official site.
On the bottom of our post’s detail page, we make use of Kirby’s YAML capabilities - by accessing the “RecommendedReading” data field and parsing it as YAML:
Kirby then provides this data in a PHP-friendly way - as an array of items that we can cycle through:
$recommendedArticles = $page->recommendedreading()->yaml();
foreach($recommendedArticles as $recommendedArticle):
As you’ve noticed above, we haven’t used page titles to identify the items we want to recommend. Instead, we’ve used the pages’ URIs (e.g. “posts/pencil”), the relative URLs without the host or any subfolders. The URI makes both for a more reliable and unique piece of data - and it can easily be fed into the “find” method to get hold of the actual page object: