LoginSignup
0
0

More than 1 year has passed since last update.

ページネーション

Last updated at Posted at 2023-01-17

ページネーションとは

  • ページを複数に分割することができるもの
  • レイアウトを調整したるするのに便利
  • グーグルのページなどの下部に表示されているやつ
    スクリーンショット 2023-01-18 3.29.45.png

実装方法

  • kaminariというgemを使用する
Gemfile
gem 'kaminari','~> 1.2.1'
$ bundle install
  • 設定ファイルを作成する
    下記コマンドで作成されたフォルダの中にページネーションの部分のhtmlが記述されているので変更を行う際は適宜修正する
$ rails g kaminari:config
  • kaminariのテンプレを作成
$ rails g kaminari:views default
  • controllerで、ページネーションを表示させたいデータに.page(params[:page])を追加する
def index
    @posts = Post.page(params[:page])
end

viewでページネーションを表示させたいところに<%= paginate @posts %>を追加します。

<h1>投稿一覧</h1>
<ul>
 <% @posts.each do |post| %>
   <li><%= post.content %></li>
 <% end %>
</ul>
<%= paginate @posts %>

以上でページネーションを実装できる。

  • 1ページに表示するレコード数はデフォルトで25件ですが、これを指定したレコード数にしたい場合は、先程作成したファイルに以下1文を追加する(1ページ6件に指定したい場合)
config/initializers/kaminari_config.rb
# frozen_string_literal: true

Kaminari.configure do |config|
  # config.default_per_page = 25
  # config.max_per_page = nil
  # config.window = 4
  # config.outer_window = 0
  # config.left = 0
  # config.right = 0
  # config.page_method_name = :page
  # config.param_name = :page
  # config.max_pages = nil
  # config.params_on_first_page = false
  config.default_per_page = 6  #ここを追加
end

デザインを変更したい場合

  • Gemfileに以下1文を追記
Gemfile
  gem 'bootstrap4-kaminari-views'
$   bundle install

paginateヘルパーに以下の以下の記述をする。

  <%= paginate @posts, theme: 'twitter-bootstrap-4' %>

↓このような見た目にできます
スクリーンショット 2023-01-18 3.51.32.png

ラベルのアイコン化

  • ラベルをアイコン化してシンプルなデザインに変更
  • Font Awesomeを読み込ませて下記を追加する
config/locales/ja.yml
ja:
  views:
    pagination:
      first: <i class="fas fa-angle-double-left"></i>
      last: <i class="fas fa-angle-double-right"></i>
      previous: <i class="fas fa-angle-left"></i>
      next: <i class="fas fa-angle-right"></i>
      truncate: "..."

このような見た目になる。
スクリーンショット 2023-04-23 18.44.44.png

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