Skip to content

Instantly share code, notes, and snippets.

@johnkoht
Created January 31, 2015 22:50
Show Gist options
  • Save johnkoht/786c3017bea22a294075 to your computer and use it in GitHub Desktop.
Save johnkoht/786c3017bea22a294075 to your computer and use it in GitHub Desktop.
Paginating categories in middleman blog
# In config.rb
def get_locals(category, total_pages, i, articles, total_articles)
prev_page = false
# Is the a previous page and if so what does it look like
if (i - 1) == 1
prev_page = "/blog/categories/#{category}"
elsif (i - 1) > 1
prev_page = "/blog/categories/#{category}/page/#{i-1}"
end
# Return the local variables
{
page_articles: articles,
paginate: total_pages > 1,
category: category,
page_number: i,
num_pages: total_pages,
next_page: if (i + 1) <= total_pages then "/blog/categories/#{category}/page/#{i+1}" else false end,
prev_page: prev_page,
total_articles: total_articles
}
end
ready do
per_page = 10
# Loop through all articles and group them by category and then loop through each group
blog.articles.group_by {|a| a.data.category }.each do |category, articles|
total_pages = articles.size.fdiv(per_page).ceil # Calculate the numer of pages
total_articles = articles.size
page_articles = articles.slice(0, per_page) # Get the articles for the page
# Create a proxy for the main/first category page
proxy "/blog/categories/#{category}.html", "/category.html", locals: get_locals(category, total_pages, 1, page_articles, total_articles)
# Create pages for each of the pagination
(1..total_pages).each do |i|
page_articles = articles.slice((i - 1) * per_page, per_page)
proxy "/blog/categories/#{category}/page/#{i}", "/category.html", locals: get_locals(category, total_pages, i, page_articles, total_articles)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment