【问题标题】:Rails3: How to pass param into custom will_paginate renderer?Rails3:如何将参数传递给自定义 will_paginate 渲染器?
【发布时间】:2011-10-13 15:43:12
【问题描述】:

我有一个自定义 will_paginate 渲染器,它会覆盖 WillPaginate::ViewHelpers::LinkRenderer 的链接方法,如下所示:

   def link(text, target, attributes = {})
      "<a href='/users/95/friends_widget?page=#{target}' rel='next' data-remote='true'>#{text}</a>"
   end

...效果很好,只是您可以在该链接中看到硬编码的 95。如何通过 Rails 视图将参数(例如用户或用户 ID)传递到自定义渲染器?

<%= will_paginate(@user_friends, :remote => true, :renderer => FriendsRenderer) %>

或者有什么我遗漏的东西,一些更简单的方法吗?

顺便说一句:@user_friends 在自定义渲染器中不可用,我已经尝试在 will_paginate 调用的末尾添加参数,例如:user => 用户)

【问题讨论】:

    标签: ruby-on-rails-3 will-paginate renderer


    【解决方案1】:

    will_paginate 允许您为链接传递 :params

    will_paginate(@user_friends, :params => { :user_id => 95 })
    

    【讨论】:

    • 你知道传递变量而不是整数的方法吗?例如 text_field 的值?
    • @GokhanArik 你是什么意思?您应该可以使用will_paginate(@user_friends, :params =&gt; { :anything =&gt; "hello" }),然后分页链接将类似于“/friends?page=2&anything=hello”。然后朋友页面可以根据需要将文本字段的值设置为params[:anything]
    • 我想传递 f.text_field 的值而不是“hello”。那可能吗?你可以看看我发布的问题-stackoverflow.com/questions/27747939/…
    【解决方案2】:

    查看:

    <%= will_paginate @user_friends, :renderer => 'FriendsRenderer',
                             :remote => true,
                             :link_path => friends_widget_user_path(@user) %>
    
    class FriendsRenderer < WillPaginate::LinkRenderer
      def prepare(collection, options, template)
        @link_path = options.delete(:link_path)
        super
      end
    
    protected
      def link(page, text, attributes = {})
        # Here you can use @link_path   
      end
    end
    

    请注意,这适用于 will-paginate 版本:2.3.6

    【讨论】:

    猜你喜欢
    • 2017-11-24
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-20
    • 2021-08-18
    • 1970-01-01
    相关资源
    最近更新 更多