LoginSignup
7
6

More than 5 years have passed since last update.

padrino+will_paginate+bootstrap向けにカスタムレンダラを実装

Posted at

目標

padrinoでwill_paginateを使ってページ処理をする。
ついでに、bootstrap用のCSSスタイルを適用するために、
カスタムレンダラを使用する。

不思議現象

windows、ruby1.9.3のpadrinoで、will_paginateを使うと、なぜか埋め込まれるべきHTMLコードがそのまま画面に出てくる。

テストユーザー13   (経理部)
テストユーザー14   (経理部)
<div class="pagination"><span class="previous_page disabled">&#8592; Previous</span> <em class="current">1</em> <a rel="next" href="/users/?page=2">2</a> <a href="/users/?page=3">3</a> <a href="/users/?page=4">4</a> <a href="/users/?page=5">5</a> <a href="/users/?page=6">6</a> <a href="/users/?page=7">7</a> <a href="/users/?page=8">8</a> <a href="/users/?page=9">9</a> <span class="gap">&hellip;</span> <a href="/users/?page=133">133</a> <a href="/users/?page=134">134</a> <a class="next_page" rel="next" href="/users/?page=2">Next &#8594;</a></div>

これでは困るので、とりあえず
= will_paginate(@collections).html_safe
と html_safe を追加してやり過ごす。

 テストユーザー14   (経理部)
← Previous 1 2 3 4 5 6 7 8 9 … 133 134 Next →

ついでにbootstrapのpaginate用CSSを利用したい!

will_paginate-bootstrapで、
gemとして公開しているものがあるけど、自分の環境ではうまく動かなかった。
なので、直接カスタムレンダラを作成することに。

カスタムレンダラについては本家のhttps://github.com/mislav/will_paginate/issues/158で話題にあり、その中でrails用に作成していただいているgist https://gist.github.com/1248807があり、そのgistのコメント欄にsinatra/padrinoバージョンhttps://gist.github.com/phildionne/5785087を公開している方が!!
ありがたく拝借して、ソースを丸のままルートにあるlibフォルダ内にbootstrap_renderer.rbなどとして設置。
テンプレートのwill_paginate部分も
= will_paginate(@collections,renderer: WillPaginate::ViewHelpers::BoostrapLinkRenderer).html_safe
と変更。

しかし!

will.png
こんな風に。bootstrapのpaginate cssの部分を調べると、paginate本体を構成するul>liを、さらにDIVでくるんで、そのDIVにpaginateクラスを適用するみたい。
それに対し、先ほど設置したカスタムレンダラのhtmlコードを見ると、ulタグ自身にpaginateクラスを付けている。
なので、先ほど設置したlib/bootstrap_renderer.rbの中のdef html_containerを一部改変。

lib/bootstrap_renderer.rb
def html_container(html)
  # tag(:ul, html, container_attributes) <= もともとのコード
  tag(:div, tag(:ul, html), container_attributes)
end

DIVでくるんであげると、
will2.png
完成!

7
6
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
7
6