2
votes

I am using Jekyll to build a blog, I managed to successfully implement a Next and Previous links on my layouts pages (using this answer). I've added several categories (using this answer) and each page iterates through the proper categories displaying only what I want them to.

My only problem now is that Previous and Next buttons still iterate through all the posts regardless of what category they are in.

This is the code I used for the Next and Previous links on the bottom of the layout:

        {% if page.previous %} 
          <span class="previous-link">
            <a rel="prev" href="{{ page.previous.url }}">Previous Entry</a>
          </span>
        {% endif %}
        {% if page.next %} 
          <span class="next-link">
            <a rel="next" href="{{ page.next.url }}">Next Entry</a>
          </span>
        {% endif %}

Is there a way to make the Next and Previous buttons go to the next or previous post in the current posts' category?

2

2 Answers

6
votes

After a bit of research. I found exactly what I was looking for on this blogpost - http://ajclarkson.co.uk/blog/jekyll-category-post-navigation/

Just needed to add a plugin to the _plugin directory and add this bit of code in it:

module Jekyll
  class WithinCategoryPostNavigation < Generator
    def generate(site)
      site.categories.each_pair do |category, posts|
        posts.sort! { |a,b| b <=> a}
        posts.each do |post|
          index = posts.index post
          next_in_category = nil
          previous_in_category = nil
          if index
            if index < posts.length - 1
              next_in_category = posts[index + 1]
            end
            if index > 0
              previous_in_category = posts[index - 1]
            end
          end
          post.data["next_in_category"] = next_in_category unless next_in_category.nil?
          post.data["previous_in_category"] = previous_in_category unless previous_in_category.nil?
        end
      end
    end
  end
end

And instead of using page.next.url and page.prev.url in the HTML, just use page.next_in_category.url and page.previous_in_category.url.

I hope this helps anyone experiencing the same issue.

4
votes

The ajclarkson plugin for pagination within categories is a correct and useful solution if you are able to install plugins.

If you want to deploy to Github pages, you cannot use plugins.

I use this method to paginate within categories. This makes sure that a post from a different category will never show up:

{% if page.next and page.next.categories contains "blog" %}

  <a href="{{ page.next.url }}">Next Post</a>

{% else if page.previous and page.previous.categories contains "blog" %}

  <a href="{{ page.previous.url }}">Previous Post</a>

{% endif %}

Be aware, this solution will not find a next post if it would have to skip over something from a different category. It avoids the worst (?) scenario, which is linking to something unintentional/not-really-a-post.