This site was built on Jekyll – a blog aware static site generator. When I was building this, I wanted to separate my blog from my portfolio. Of course I would be using custom post type for my portfolio if I was developing on WordPress. Here I thought to stay straight and simple and I just created two site categories: portfolio and blog and I am using custom permalink which makes it difficult to use the default pagination setup. And I also want to paginate only the blog category.

Here, in this tutorial, we will discuss on how to paginate a specific category in Jekyll with custom plugin built from scratch.

Let’s get started.

Site Structure

In order for the plugin to work, I have removed the index.html from blog category (i.e. directory). Now my site structure looks like this:

I want the index.html in the blog category to be generated by the plugin. Here is the site structure I wish to have:

As you can see, index.html in the blog category will be generated by the plugin as the very first page of the pagination. And from second page onward, it will live in respective directories under pages directory.

Liquid Template

The template for iterating over the current set of posts and showing them look like this:

There should also be navigation links for previous and next pages. Here goes the template for that:

I include these templates in a heredoc inside my plugin.

The Configuration

Before diving into writing the plugin, we need to set some config options in the _config.yml file to make the plugin a bit more maintainable.

We need to provide an option to later modify number of posts in a page without touching the plugin. For this reason, we are going to include posts_per_page in our _config.yml.

The setting paginated_category will tell the plugin which category to use for pagination. We may hardcode this in our plugin, but it is a bit more professional to provide an option to change the setting later without looking at the plugin.

The Code

First, create a file CategoryPostPaginator.rb inside your _plugins directory.

The first class to create is the “Generator.” All generators are called by Jekyll at site build, so if you want code that’s going to create new pages or content, you want to sub-class this class.

When Jekyll calls a generator, it calls the generate method, so that’s the first method to implement. In our class, it loops through all the posts in the site and group the posts according to their position (or index). Then it crates a page for each group.

Next, we need to subclass the Page class for our specific needs. This code is very specific to my site, you may want to change the logic here to meet your needs. Basically, I am creating a series of pages to show category indexes. This code customizes the layout that’s used and adds some information to the generated page. I have included my liquid template in heredoc statement.

That is the end of our discussion. Hope you enjoyed it. Just give it a try.

The Author

Other Articles