Skip to content

Instantly share code, notes, and snippets.

@mmonge
Created January 19, 2016 04:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmonge/0424bde855c1cbcca469 to your computer and use it in GitHub Desktop.
Save mmonge/0424bde855c1cbcca469 to your computer and use it in GitHub Desktop.
Jekyll Plugin Generator - Next and previous pagination by category
# A plugin to obtain category pagination with Jekyll
#
# Usage:
# <ul class="pagination">
# {% if page.blog_previous %}
# <li class="prev"><a href="{{ page.blog_previous.url | prepend: site.baseurl }}" title="{{ page.blog_previous.title }}">&laquo; Previous</a></li>
# {% else %}
# <li class="prev disabled"><a>&larr; Previous</a></li>
# {% endif %}
# <li><a href="{{ "/blog/" | prepend: site.baseurl }}">Blog</a></li>
# {% if page.blog_next %}
# <li class="next"><a href="{{ page.blog_next.url | prepend: site.baseurl }}" title="{{ page.blog_next.title }}">Next &raquo;</a></li>
# {% else %}
# <li class="next disabled"><a>Next &rarr;</a>
# {% endif %}
# </ul>
module Jekyll
class CategoryPrevNextGenerator < Generator
safe true
priority :high
def generate(site)
site.categories.each_pair do |category_name, posts|
# print "> " + category_name + ":\n"
posts.sort! { |a, b| b <=> a }
posts.each_with_index do |post, index|
# print "-> " + post.data['date'].to_s + ": " + post.data['title'] + "\n"
# print "--: " + index.to_s + "\n"
# Previous
if index < posts.length - 1
category_prev = posts[index + 1]
else
category_prev = nil
end
# Next
if index > 0 && posts.length > 1
category_next = posts[index - 1]
else
category_next = nil
end
post.data["#{category_name}_previous"] = category_prev unless category_prev.nil?
post.data["#{category_name}_next"] = category_next unless category_next.nil?
end # / posts each
end # / categories each
end # / method generate
end # / class
end # / module
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment