Pagination for Timber Posts Module

The Timber Posts Module is probably the single most powerful module in the Toolbox plugin. It allows you to do virtually anything. Because nothing is really fixed inside the Timber Posts module it serves no purpose to add pagination at the top or bottom of the results, you can just as easily add it in the middle of the results or multiple times.

Here’s how you can do that.

Make sure to install and activate the Timber-library plugin before you continue

Most examples like the ones in this post are using the UIKit CSS and JS-library. It makes development very fast and adds interactive features with classes and attributes. More on UIkit on their website.

If you want to test UIkit you can also download the bb-uikit plugin from my Github Repository.

  1. Add a Timber Posts Module to your layout and set the Custom Query or use the Main Query when you’ve placed the Timber Posts Module on a Archive or Search Results Themer Layout.
  2. Add your template for the display of the posts results

If you’ve done this and there are more results than that are set in the “Posts per Page” (module)setting  or “Blog pages show at most” (WP Dashboard > Settings > Reading) you will need to add pagination. To do so, save this template as is for now.

After saving the module and layout, go back to the WP Dashboard and add a new Twig Template.

Insert the following template:

{% macro pagination(posts) %}
{% if posts.pagination and posts.pagination.total > 1 %}
<ul class="uk-pagination uk-flex-center uk-margin-medium-top" uk-margin>
{% if posts.pagination.current == 1 %}
<li></li>
{% else %}
<li><a href="{{posts.pagination.prev.link}}"><span uk-pagination-previous></span></a></li>
{% endif %}
{% for page in posts.pagination.pages %}
<li class="{{(page.title==posts.pagination.current)?'current'}}"><a href="{{page.link}}">{{page.title}}</a></li>
{% endfor %}
{% if posts.pagination.current == posts.pagination.total %}
<li></li>
{% else %}
<li><a href="{{posts.pagination.next.link}}"><span uk-pagination-next></span></a></li>
{% endif %}
</ul>
{% endif %}
{% endmacro %}

Give it a Title and Save the Twig template. After saving it, make note of the Twig’s slug or copy it to the clipboard. Let’s assume your slug is called “pagination”

Now go back to the Timber Posts Module you edited earlier.

Add the following line to the top of the template:

{% import 'pagination.twig' as navi %}

This loads the Twig Template with the slug called “pagination” into memory, under a variable called navi.

Now you can put pagination links anywhere in your module, for instance at the very bottom, by adding:

{{ navi.pagination( posts ) }}

Beaverplugins

Web ninja with PHP/CSS/JS and Wordpress skills. Also stand-in server administrator, father of four kids and husband to a beautiful wife. Always spends too much time figuring out ways to do simple things even quicker. So that you can benefit.