Twitter Bootstrap を使って Pagination を作る

材料


Flask の Snippet にある Simple Pagination を utils/pagintion.py とかにして保存する。

# -*- coding: utf-8 -*-
from flask import Flask
from utils.pagination import Pagination
from models.items import Items

LIMIT = 50

app = Flask(__name__)

def url_for_other_page(page):
    args = request.view_args.copy()
    args['page'] = page
    return url_for(request.endpoint, **args)
app.jinja_env.globals['url_for_other_page'] = url_for_other_page

@app.route('/', methods=['GET'], strict_slashes=False)
@app.route('/page/<int:page>/', methods=['GET'], strict_slashes=False)
def index(page):
    items = Items()
    offset = (int(page) - 1) * limit

    #: Items の総件数
    total = items.count()
    #: Items のデータ
    rows = items.find_all(limit=LIMIT, offset=offset)
    pagination = Pagination(page, limit, total)

    return render_template('index.html', rows=rows, pagination=pagination)

Pagination の部分を毎回テンプレートに書いても良いが、同じようなのを毎回書くのはめんどくさいので、マクロ化してインポートするようにする。
templates/pagination.html とかにした。

{% macro render_pagination(pagination) %}
<div class="pagination">
  <ul>
  {% if pagination.has_prev %}
    <li class="prev">
      <a href="{{ url_for_other_page(pagination.page - 1) }}">&laquo; Prev</a>
    </li>
  {% endif %}
  {%- for page in pagination.iter_pages() %}
    {% if page %}
      {% if page == pagination.page %}
      <li class="active"><a href="{{ url_for_other_page(page) }}">{{ page }}</a></li>
      {% else %}
        <li><a href="{{ url_for_other_page(page) }}">{{ page }}</a></li>
      {% endif %}
    {% else %}
      <li class="prev disabled"></li>
    {% endif %}
  {%- endfor %}
  {% if pagination.has_next %}
    <li class="next">
      <a href="{{ url_for_other_page(pagination.page + 1) }}">Next &raquo;</a>
    </li>
  {% endif %}                                                
  </ul>
</div>
{% endmacro %}

templates/index/index.html

-略-
{% import '/index/pagination.html' as p %}
{{ p.render_pagination(pagination) }}

とかすると Pagination が生成する。