PJCHENder 未整理筆記

[Gem] kaminari

2017-12-26

[Gem] kaminari

@(Ruby on Rails)[Rails]

Kaminari @ GitHub

安裝

1
2
3
# Gemfile
# Kaminari is a Scope & Engine based, clean, powerful, agnostic, customizable and sophisticated paginator for Rails 4+
gem 'kaminari', '~> 1.1', '>= 1.1.1'

設定

1
2
# 產生設定檔
bin/rails g kaminari:config # create config/initializers/kaminari_config.rb

使用

Controller 中把需要分頁的頁面,從原本的 @posts = Post.all 改成 @posts = Post.all.page(params[:page])

1
2
3
4
5
6
7
8
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
def index
# @posts = Post.all
@posts = Post.all.page(params[:page])
respond_to :html, :js
end
end

View 中把需要分頁的頁面加入:<%= paginate @posts %>,接著就會產生醜醜的 view 了:

Imgur

產生好看的分頁

可以在 kaminari themes 中看看有沒有支援的主題

1
2
bin/rails g kaminari:views <THEME>
bin/rails g kaminari:views bootstrap4

Issues

原本的 paginator 沒辦法載到正確的 css class,需要加上 href: 'javascript:;

1
2
3
4
5
6
7
8
9
10
<!-- OnePageShop/app/views/kaminari/_page.html.erb -->
<% if page.current? %>
<li class="page-item active">
<%= content_tag :a, page, href: 'javascript:;', remote: remote, rel: (page.next? ? 'next' : (page.prev? ? 'prev' : nil)), class: 'page-link' %>
</li>
<% else %>
<li class="page-item">
<%= link_to page, url, remote: remote, rel: (page.next? ? 'next' : (page.prev? ? 'prev' : nil)), class: 'page-link' %>
</li>
<% end %>

加上 i18n

/OnePageShop/config/locales/ 中加上這兩隻檔案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# OnePageShop/config/locales/kaminari.en.yml
en:
views:
pagination:
first: "&laquo; First"
last: "Last &raquo;"
previous: "&lsaquo; Prev"
next: "Next &rsaquo;"
truncate: "&hellip;"
helpers:
page_entries_info:
one_page:
display_entries:
zero: "No %{entry_name} found"
one: "Displaying <b>1</b> %{entry_name}"
other: "Displaying <b>all %{count}</b> %{entry_name}"
more_pages:
display_entries: "Displaying %{entry_name} <b>%{first}&nbsp;-&nbsp;%{last}</b> of <b>%{total}</b> in total"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# OnePageShop/config/locales/kaminari.zh-TW.yml
zh-TW:
views:
pagination:
first: "&laquo; 第一頁"
last: "最後一頁 &raquo;"
previous: "&lsaquo; 上一頁"
next: "下一頁 &rsaquo;"
truncate: "&hellip;"
helpers:
page_entries_info:
one_page:
display_entries:
zero: "找不到 %{entry_name}"
one: "只有 <b>1</b> 筆 %{entry_name}"
other: "顯示 <b>所有 %{count}</b> 筆 %{entry_name}"
more_pages:
display_entries: "顯示 <b>%{first}&nbsp;-&nbsp;%{last}</b> 筆 %{entry_name},共 <b>%{total}</b> 筆"

掃描二維條碼,分享此文章