如何使用 will_paginate gem 实现 ajax 分页 [英] How to Implement ajax pagination with will_paginate gem

查看:28
本文介绍了如何使用 will_paginate gem 实现 ajax 分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 ROR 项目中使用 will_paginate gem 来显示页面中的记录.

I am using will_paginate gem in my ROR project to show the records in pages.

我希望无需使用 ajax 重新加载整个页面即可加载下一页.

I want the next page to be loaded without reloading the whole page using ajax.

我在网上找到了一些例子,但它们对我不起作用.

I found some examples on the net but they don't work for me.

如何做到这一点?

推荐答案

创建一个新的助手(例如 app/helpers/will_paginate_helper.rb),内容如下:

Create a new helper (ex. app/helpers/will_paginate_helper.rb) with the following content:

module WillPaginateHelper
  class WillPaginateJSLinkRenderer < WillPaginate::ActionView::LinkRenderer
    def prepare(collection, options, template)
      options[:params] ||= {}
      options[:params]['_'] = nil
      super(collection, options, template)
    end

    protected
    def link(text, target, attributes = {})
      if target.is_a? Fixnum
        attributes[:rel] = rel_value(target)
        target = url(target)
      end

      @template.link_to(target, attributes.merge(remote: true)) do
        text.to_s.html_safe
      end
    end
  end

  def js_will_paginate(collection, options = {})
    will_paginate(collection, options.merge(:renderer => WillPaginateHelper::WillPaginateJSLinkRenderer))
  end
end

然后在您的视图中使用此标签进行 ajax 分页:

Then in your view use this tag for ajax pagination:

<%= js_will_paginate @recipes %>

请记住,分页链接将包含 url 的现有参数,您可以排除这些,如下所示.这是标准的分页功能:

Remember that the pagination links will include existing params of the url, you can exclude these as shown below. This is standard will paginate functionality:

<%= js_will_paginate @recipes, :params => { :my_excluded_param => nil } %>

希望能解决您的问题.

更新 1:在 原始问题 我在哪里发布了这个解决方案.

Update 1: Added a explanation of how this works to the original question where I posted this solution.

更新 2:我已使其 Rails 4 与 remote: true links 兼容,并将辅助方法重命名为 js_will_paginate.

Update 2: I've made it Rails 4 compatible with remote: true links and renamed the helper method to js_will_paginate.

这篇关于如何使用 will_paginate gem 实现 ajax 分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆