Skip to content

Instantly share code, notes, and snippets.

@aaronrussell
Created June 30, 2011 08:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aaronrussell/1055853 to your computer and use it in GitHub Desktop.
Save aaronrussell/1055853 to your computer and use it in GitHub Desktop.
Nanoc pagination
module PaginationHelper
# The main pagination method, you should only need to call this
# Returns full HTML markup for pagination links
def pagination(page, pages, uri)
html, ul = [], []
html << pagination_position(page, pages)
if pages > 1
ul << pagination_previous_link(page, uri)
ul << pagination_page_links(page, pages, uri)
ul << pagination_next_link(page, pages, uri)
html << content_tag(:ul, ul.join)
end
content_tag :nav, html.join, :id => "pagination"
end
# Returns paragraph with pagination position
def pagination_position(page, pages)
content_tag :p, "Page #{page} of #{pages}"
end
# Returns the "previous" pagination link
def pagination_previous_link(page, uri)
text = "&laquo; Prev"
content_tag :li, (page > 1 ? link_to(text, "#{uri}page/#{page-1}") : content_tag(:span, text)), :class => "prev"
end
# Returns the "next" pagination link
def pagination_next_link(page, pages, uri)
text = "Next &raquo;"
content_tag :li, (page < pages ? link_to(text, "#{uri}page/#{page+1}") : content_tag(:span, text)), :class => "prev"
end
# Returns all the page number pagination links
def pagination_page_links(page, pages, uri)
visible_page_numbers(page, pages).collect do |pg|
content_tag(:li, link_to(pg, "#{uri}page/#{pg}"), :class => ("current" if pg == page))
end.join
end
# Returns an array of visible page numbers
# Borrowed from will_paginate implementation
# https://github.com/mislav/will_paginate/blob/master/lib/will_paginate/view_helpers.rb
def visible_page_numbers(current_page, total_pages)
inner_window, outer_window = 4, 4
window_from = current_page - inner_window
window_to = current_page + inner_window
# adjust lower or upper limit if other is out of bounds
if window_to > total_pages
window_from -= window_to - total_pages
window_to = total_pages
end
if window_from < 1
window_to += 1 - window_from
window_from = 1
window_to = total_pages if window_to > total_pages
end
visible = (1..total_pages).to_a
left_gap = (2 + outer_window)...window_from
right_gap = (window_to + 1)...(total_pages - outer_window)
visible -= left_gap.to_a if left_gap.last - left_gap.first > 1
visible -= right_gap.to_a if right_gap.last - right_gap.first > 1
visible
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment