Paginating long posts
Split long post into separate pages with pagination
In many online publications, long posts are split across multiple pages with pagination at the bottom. How can we achieve this in Kirby?
In this example, we will insert manual page breaks where we want to split the post. We take the notes section from the starterkit as our example setup.
note post, add an HTML comment where you want to paginate:
Add a new
note.php controller in
note.php template, we have to make three changes.
First, we loop through the parts we defined in the controller:
<?php foreach ($parts as $part): ?> <!-- rest of code --> <?php endforeach ?>
Secondly, we replace the original line where we displayed the complete text…
<?= $page->text()->kirbytext() ?>
with just the part of the text:
<?= $part ?>
And finally, we add the pagination with links for the previous and next pagination pages at the bottom:
<nav class="pagination"> <?php if ($pagination->hasPrevPage()): ?> <a href="<?php echo $pagination->prevPageUrl() ?>">‹ previous page</a> <?php endif ?> <?php if ($pagination->hasNextPage()): ?> <a href="<?php echo $pagination->nextPageUrl() ?>">next page ›</a> <?php endif ?> </nav>
Here is the complete template:
Instead of using manual page breaks, you could split your text by other criteria, e.g after every x paragraphs, number of words or characters, before subheading etc.
Or you could add a little table of contents on each page.
You can also extend the pagination navigation and add a numbered link for each page, making use of the
$pagination->range() method. You can find an example in our pagination recipe.