LoginSignup
0
0

More than 1 year has passed since last update.

【Rails 7】will_paginate の Turbolinks を無効化する方法

Last updated at Posted at 2022-09-30

開発環境

・Ruby: 3.1.1
・Rails: 7.0.3.1
・OS: Windows 10
・Docker

will_paginate の Turbolinks を無効化する方法

簡単に will_paginate の記載に data: { turbo: false } を追加したら、turbolinksは無効化されません。

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

なぜなら、上記はそれぞれのページネーションボタンリンクではなく、外の paginate divdata="{:turbo=>false}"の属性を追加するからです。turbolinksを無効化するために、それぞれのページネーションボタンリンクに data-turbofalse にする必要があります。

そうするためのショットカットがまだないので will_paginaterenderer をカスタマイズする必要があります。

will_paginaterenderer をカスタマイズする:

1. カスタムレンダラーを作成する
li タグの data-turbo="false" が重要なポイントです。

config/initializers/custom_paginate_renderer.rb
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

2. カスタムのレンダラーを 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

...省略...

3. サーバーを再起動する

これで、will_paginate のページネーションリンクの turbolinks が無効化されます。


参考:

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0