Back to Blogs
#rails#css#webdev#beginners

Easy Custom Pagination: Paginator Fancinator!

Pagination allows you to navigate through multiple pages of search results. It increases user...

2 min read
Cover for Easy Custom Pagination: Paginator Fancinator!

Pagination allows you to navigate through multiple pages of search results. It increases user experience, instead of have 100 things on a page.

I was very excited to learn of the kaminari gem, which helps you implement a quick pagination. I used the default at first, but after styling my page, of course it became an eye sore.

The kaminari gem has a few built in themes you can choose. You can choose a theme or create your own! It's very simple. After adding kaminari, you can set up views for tweaking styling.

Start

Run rails g kaminari:views in your rails app.

You can investigate the options:

kaminari views

Now there is a list of themes, pick one, and add that to the end of the command in the terminal. This will generate a bunch of views as partials for you to play with.

What these views do for you is give you specific access to all of the links/buttons on the paginator. For me, I have an events page and I am paginating the search results. On my events page I add the following line to where I want the paginator to live:

<%= paginate @events, partial: 'events/paginator' %>

So then, I had to do some digging to get this to work right. I'll spare you the suffering. XD

Kaminari has the following helper methods so you don't have to create them:

  • page
  • prev_page
  • next_page

Now, we can easily render conditionals in our paginator partial to display the appropriate items.


<nav class="custom-pagination">
  <%# Render the "Previous" link if there's a previous page %>
  <% if @events.prev_page %>
    <%= link_to "Previous", url_for(page: @events.prev_page), class: "prev-page" %>
  <% else %>
    <span class="prev-page disabled">Previous</span>
  <% end %>

  <%# Render each page link %>
  <% paginator.each_page do |page| %>
    <% if page.current? %>
      <span class="current-page"><%= page %></span>
    <% else %>
      <%= link_to page, url_for(page: page), class: "page-link" %>
    <% end %>
  <% end %>

  <%# Render the "Next" link if there's a next page %>
  <% if @events.next_page %>
    <%= link_to "Next", url_for(page: @events.next_page), class: "next-page" %>
  <% else %>
    <span class="next-page disabled">Next</span>
  <% end %>
</nav>


Enter fullscreen mode Exit fullscreen mode

All the fancies

Now you can manipulate the links as you see fit with your custom css classes!

fun paginator

Totally worth it.