自定义will_paginage输出(转自rails2.cn)

自定义分页插件WillPaginate的输出与扩展
本文介绍了如何通过扩展WillPaginate::LinkRenderer类来自定义分页插件WillPaginate的输出样式,包括去除Next和Previous链接、在分页链接后显示文本框与直接跳转功能,以及提供了更复杂自定义Renderer的实现方法。
自定义will_paginage输出

ill_paginate是Rails中比较常用的分页插件,但是有时候我们可能想要自定义它的输出,这可以通过扩展WillPaginate::LinkRenderer类来实现,比如,下面的renderer将会去除Next和Previous链接:

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


要在view中使用这个自定义的renderer,只需要加上:renderer参数即可:


<%= will_paginate @items, ;:renderer => ‘CustomPaginationRenderer’ %>


下面给出一个更复杂的自定义Renderer,它会在分页链接后显示一个文本框,以及一个‘Goto’按钮,允许用户直接跳转到某一页:


class CustomPaginationRenderer < 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"&gt
function goto_page#{@@id}()
{
page = Number($(’page#{@@id}’).value)
total = #{total_pages}
if(page < 1 || page > total)
{
alert(’Please enter a number between 1 and ‘ + total + ‘!’)
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


@@id的作用是因为一个view中有可能多次调用will_paginate,需要对inputbox进行区分,这个renderer还用到了一些继承自WillPaginate::LinkRenderer的方法:

url_for(page), 返回指向某页的链接,比如url_for(1) => ‘/posts?page=1′
total_pages, 返回总页数
page_link_or_span,返回指向某页面的链接
更多方法可以在WillPaginate的view_helper.rb中找到。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值