Will_paginate自定义(转帖)

1.功能:分页链接后显示一个文本框,以及一个‘Goto’按钮,允许用户直接跳转到某一页.

class CustomPaginate < WillPaginate::LinkRenderer
@@id = 1
def to_html
links = @options[:page_links] ? windowed_links : []
# previous/next buttons
links.unshift page_link_or_span(@collection.previous_page, 'disabled', @options[:prev_label])
links.push page_link_or_span(@collection.next_page, 'disabled', @options[:next_label])
html = links.join(@options[:separator])
html += goto_box
@options[:container] ? @template.content_tag(:div, html, html_attributes) : html
end

private
def goto_box
@@id += 1
@@id = 1 if @@id > 100
<<-GOTO
<input type="text" maxlength="5" size="3" id="page#{@@id}" />
<input type="submit" onclick="goto_page#{@@id}()" value="Goto"/>
<script type="text/javascript" >
function goto_page#{@@id}()
{
page = new Number(document.getElementById('page#{@@id}').value)
if(page < 1 || page > #{total_pages})
{
alert('Please enter a number between 1 and ' + #{total_pages} + ' !')
return;
}
var link = '#{@template.url_for(url_options("_page"))}'
var new_link = link.replace("_page", page)
window.location.assign(new_link)
}
</script>
GOTO
end
end

2.功能:去除Next和Previous链接.

class CustomPaginate < 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

注:在View中使用这个自定义的CustomPaginate有两种方法.
第一种:在will_paginate中使用:renderer参数.

<%= will_paginate @products, :prev_label => '«前', :next_label => '次»', :renderer => 'CustomPaginate' %>

第二种:在config/environment.rb中设置自定义的renderer.

WillPaginate::ViewHelpers.pagination_options[:renderer] = 'CustomPaginate'.

参考来源