Flask-Paginate

2024.4.12 · active · verified Thu Apr 16

Flask-Paginate provides simple pagination support for Flask applications, making it easy to display large datasets across multiple pages. It handles page number generation, URL building, and integrates with various CSS frameworks like Bootstrap. The current version is 2024.4.12, following a date-based release cadence with frequent updates for bug fixes and compatibility.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart sets up a basic Flask application with pagination for a list of 100 users. It demonstrates how to retrieve the current page number, slice the data accordingly, and initialize the `Pagination` object. It uses Bootstrap 4 for styling and renders the pagination controls directly using `pagination.render_macro('pagination.html')`.

import os
from flask import Flask, render_template, request
from flask_paginate import Pagination, get_page_parameter

app = Flask(__name__)
app.secret_key = os.environ.get('FLASK_SECRET_KEY', 'a_secret_key_for_dev')

# Sample data
USERS = [str(i) for i in range(1, 101)]

@app.route('/')
def index():
    page = request.args.get(get_page_parameter(), type=int, default=1)
    per_page = 10
    offset = (page - 1) * per_page
    
    users_for_page = USERS[offset:offset + per_page]
    total = len(USERS)

    pagination = Pagination(
        page=page, per_page=per_page, total=total,
        css_framework='bootstrap4',
        record_name='users'
    )

    # In a real app, you would have an 'index.html' template
    # For this example, we'll return a minimal string.
    # In your template, you would use: {{ pagination.render_macro('pagination.html') }}
    return f"""<!doctype html>
<html lang='en'>
<head>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no'>
    <link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css' integrity='sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N' crossorigin='anonymous'>
    <title>Flask-Paginate Example</title>
</head>
<body>
    <div class='container'>
        <h1>Users</h1>
        <ul>
            {''.join([f'<li>User {user}</li>' for user in users_for_page])}
        </ul>
        <div class='text-center'>
            {pagination.render_macro('pagination.html')}
        </div>
    </div>
</body>
</html>"""

if __name__ == '__main__':
    app.run(debug=True)

view raw JSON →