Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kaminari pagination control with fixed page link count

I would like to have Kaminari to show pagination links at fixed count with pagination control, for example 10 links on each navigation page. Kaminari default shows 6 page links at first page and the page links continue to grow when you continue browsing until you reach 9 items.

I show in picture here, when I first load it will have 5 links in total.

enter image description here

When I continue to browse, it will grow.

enter image description here

Until you browse for the 5th link, it only show total links of 9.

enter image description here

How do I consistently have a link count of 10 even at the beginning or the end of the navigation with Kaminari. I have try with Kaminari config.window, but that's not what I want.

like image 202
TonyTakeshi Avatar asked Nov 15 '12 10:11

TonyTakeshi


People also ask

How can I paginate with kaminari?

Add page(params[:page]) in front get data query in controller function. 4. Add <%= paginate @attribute %> in html view and it is done. Kaminari automatically handles each and everything for it.


2 Answers

I wasn't able to get the answer above to work. What I did was to calculate the window size and pass it into my pagination partial.

controller

  window = @items.current_page < 5 ? 5 - @items.current_page : 1
  render partial: 'pagination; locals: {items: @items, window: window}

_pagination.html.slim

.col-lg-6.pull-right
  ...
  = paginate items, remote: true, window: window
  ...
like image 57
Antarr Byrd Avatar answered Sep 30 '22 12:09

Antarr Byrd


You could monkey patch Kaminari's Paginator and PageProxy classes. By overriding methods like relevant_pages, inside_window?, left_outer?, and right_outer? you can control when a page link gets shown in the paginate view helper.

To get started, create a new file in config/initializers called kaminari.rb and paste in the following code:

module Kaminari
  module Helpers
    class Paginator < Tag
      def relevant_pages(options)
        1..options[:total_pages]
      end

      class PageProxy
        def inside_window?
          if @options[:current_page] <= @options[:window]
            @page <= (@options[:window] * 2) + 1
          elsif (@options[:total_pages] - @options[:current_page].number) < @options[:window]
            @page >= (@options[:total_pages] - (@options[:window] * 2))
          else
            (@options[:current_page] - @page).abs <= @options[:window]
          end
        end
      end
    end
  end
end

It's not pretty but it gets the job done. If you set window: 5 in your view then this will always show a total of 10 links plus another <span> for the current page.

To learn more, check out the source code https://github.com/amatsuda/kaminari/blob/master/lib/kaminari/helpers/paginator.rb

like image 42
Keith Avatar answered Sep 30 '22 13:09

Keith