Disable Turbolinks for will_paginate (Rails 7)

538 Views Asked by At

Need to disable Turbolinks for the pagination buttons.

Simply adding data: { turbo: false } does not seem to work.

<% will_paginate data: { turbo: false } %>
1

There are 1 best solutions below

0
greenMaven On

The reason why <% will_paginate data: { turbo: false } %> does not work is that it puts the data-turbo attribute on the outer container div and not on the individual button links.

Although there is no shortcut to disable turbolinks for the will_paginate pagination links yet (at least I couldn't find any), the desired result can be achieved by customising the will_paginate renderer as follows.


First, create the Custom renderer: config/initializers/custom_paginate_renderer.rb. Note the data-turbo="false" attribute on the li tags. This will do the trick.

require 'will_paginate/view_helpers/action_view'
require 'will_paginate/view_helpers/link_renderer' 

class CustomPaginateRenderer < WillPaginate::ActionView::LinkRenderer
  def container_attributes
    { class: 'pagination' }
  end

  def html_container(html)
    child = tag(:ul, html, container_attributes)
    tag(:nav, child)
  end

  def page_number(page)
    if page == current_page
      '<li class="page-item active" data-turbo="false">' + link(page, page, rel: rel_value(page),class: 'page-link') + '</li>'
    else
      '<li class="page-item" data-turbo="false">' + link(page, page, rel: rel_value(page),class: 'page-link') + '</li>'
    end
  end

  def previous_page
    num = @collection.current_page > 1 && @collection.current_page - 1
  previous_or_next_page(num, '<span aria-hidden="true">&laquo;</span>')
  end

  def next_page
    num = @collection.current_page < total_pages && @collection.current_page + 1
  previous_or_next_page(num, '<span aria-hidden="true">&raquo;</span>')
  end

  def previous_or_next_page(page, text)
    if page
      '<li class="page-item" data-turbo="false">' + link(text, page, class: 'page-link') + '</li>'
    else
      '<li class="page-item disabled" data-turbo="false">' + link(text, page, class: 'page-link') + '</li>'
    end
  end
end

Next, pass this as the renderer for will_paginate: app/helpers/application_helper.rb.

def will_paginate(coll_or_options = nil, options = {})
  if coll_or_options.is_a? Hash
    options = coll_or_options
    coll_or_options = nil
  end
  unless options[:renderer]
    options = options.merge renderer: CustomPaginateRenderer
  end
  super *[coll_or_options, options].compact
end

Lastly, do not forget to restart the server for the config changes to take effect.


If anybody else knows a better way to do it, I'd be glad to hear it!


References:

https://github.com/mislav/will_paginate/wiki/Link-renderer

custom will_paginate renderer