Rendering will_paginate links without previous and next buttons

March 16, 2008

This blog post was written in 2008. Information and links in this post may be outdated.

I recently needed to build a page that had a paginated list of items. I immediately did what I always do for pagination and grabbed the will_paginate plugin (also released as a gem). 2 lines of code later and pagination was working.

Then I noticed that the design mockup I had been given did not include room for previous or next buttons, despite the fact that most pagination guides recommend using them. My first thought was to see if setting the :prev_label and :next_label to nil would work, but it still output the html tags and also output the current page number twice - not quite what I wanted.

My next thought was that I could patch the LinkRenderer - and then I realized that the folks over at err.the_blog already prepared for exactly this scenario by allowing others to write custom link renderers. Here's how it works:

In your view, add the following:

<%= will_paginate @items, :renderer => 'CustomPaginationRenderer' %>

Then, drop a file anywhere in your load path (config/initializers, lib directory, a plugin etc...) with the following code:

class CustomPaginationRenderer < WillPaginate::LinkRenderer
  def to_html
    links = @options[:page_links] ? windowed_links : []
    html = links.join(@options[:separator])
    @options[:container] ? @template.content_tag(:div, html, html_attributes) : html
  end
end

This creates a new link renderer that inherits from the default WillPaginate::LinkRenderer and overrides just one method: to_html. I just copied the to_html from the original renderer and removed the two lines that added the previous and next links.

Given the complexity of the logic behind rendering links and all of the subtle differences in the way links can be displayed, will_paginate could have been a much more complex plugin. Instead, it is simple and extremely easy to understand and extend. I highly recommend that plugin authors and paginators alike check it out.