will_paginate 3 with javascript page changing
Tuesday, November 2nd, 2010Say, you have this rails 3 application where you want to display data from one of your models with pagination and you’ve gone with will_paginate 3 (currently still in beta), but you want to go through different data pages without changing the current web page (think, comments à la youtube). You have at least two choices.
You could add some javascript fairy dust and add a click() listener to intercept the call.
If you want to stay on the Ruby side, you could use a remote link. To do so, with will_paginate, you can use a custom LinkRenderer. There’s a howto already available for remote links with will_paginate 2 but obviously, it doesn’t work with the current beta because methods have changed names. You can however follow the same steps and try to use the following code instead:
class RemoteLinkRenderer < WillPaginate::ViewHelpers::LinkRenderer
def prepare(collection, options, template)
@remote = options.delete(:remote) || { }
super
end
def link(text, target, attributes = {})
page_attr = { :page => target }
@template.link_to( text.to_s.html_safe, @remote.merge(page_attr), :remote => true )
end
end
(there’s a html_safe there, because the default next/previous text for will_paginate use html entities for arrows, otherwise it’s only numbers everywhere).