Custom pagination links
Do you know what pagination links are? They are at the bottom of web pages and allow you to scroll to a next page, and scroll back when you’re at some deep-linked page. In Rails development, you use something called Will Paginate. It has a default set of pagination links, and sometimes these just won’t do. It’s time to subclass WillPaginate::LinkRenderer.
First the wrong way to go about this. You don’t retrieve the pagination links and then hack at the resulting string. You do not find-and-replace link anchors and classes to get where you want. That is ugly, brittle, hard to understand and generally awful. You simply subclass the object that WillPaginate uses itself to render the links.
That is called the LinkRenderer and building your own is easy. This post led the way for me. My pagination needs are much simpler though. I do not need any of the page links; just previous and next. And I don’t need any inactive link. When we’re on the current page, no link should be rendered at all.
Without further ado here is the class I ended up with:
class MyPaginationLinkRenderer < WillPaginate::LinkRenderer
def to_html
links = []
# previous/next buttons, but never a disabled one
if @collection.previous_page && @collection.previous_page != current_page
links.push page_link(@collection.previous_page, 'prev')
end
if @collection.next_page && @collection.next_page != current_page
links.push page_link(@collection.next_page, 'next')
end
links.join @options[:separator]
end
private
def page_link(page, classname)
@template.link_to page.to_s, url_for(page), :rel => rel_value(page), :class => classname
end
end
As you can see, my pagination links is an array with max two items. The previous page and the next page. By overriding the to_html method, I make sure to skip most of the built-in customisable options and go straight to the code I need.
Using this renderer instead of the default one is equally easy. Since I also need the normal pagination links, I want to specify using this renderer on each and every page. So my code to render the links looks like this:
<%= will_paginate @articles, :renderer => MyPaginationLinksRenderer %>
Lastly, to use this code I stuck it into a file in config/initalizers. Custom pagination links … DONE.
Hey it a great one ya
how can i display only current page number , prev and next