DEV Community

Cover image for Pagination with Flask and Jinja2
Graham Patrick
Graham Patrick

Posted on

Pagination with Flask and Jinja2

Have you ever wondered how to display a large amount of data on your web pages without overwhelming your users? If so, you might want to learn about pagination.

Pagination is a way of breaking down your data into smaller pieces and showing them on separate pages. This way, your users can easily navigate through your data and find what they are looking for. In this article, I will show you how to implement pagination in Python using Flask and Jinja2.

Flask is a lightweight web framework that lets you create web applications with minimal code. Jinja2 is a powerful template engine that lets you generate HTML from your data using a simple syntax. Together, they make pagination a breeze. Let's get started!

Let's see how we can build a Blog model and use pagination to display the data in an html template.

# app.py
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blogs.db' # change this to your database URI
db = SQLAlchemy(app)

class Blog(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable=False)

@app.route('/blogs')
@app.route('/blogs/<int:page>')
def blogs(page=1):
    per_page = 5 # change this to the number of blogs you want to display per page
    blogs = Blog.query.paginate(page, per_page, error_out=False) # get the pagination object
    return render_template('blogs.html', blogs=blogs) # pass the pagination object to the template

Enter fullscreen mode Exit fullscreen mode

Yes, that’s right. To add the pagination links in the Jinja template, we can use the Pagination object that we passed from the Flask view function. The Pagination object has some useful attributes and methods that we can use to create the links, such as:

has_prev and has_next: These are boolean values that indicate if there is a previous or next page.

prev_num and next_num: These are the page numbers for the previous and next page, if they exist.

iter_pages(): This is a method that returns an iterator of all the page numbers, which we can use to create links to each page.

We can use these features in combination with the url_for function, which generates the URL for a given view function with optional arguments, to create the pagination links in our template. For example, we can write something like this:

<!-- blogs.html -->
<html>
<head>
    <title>Blogs</title>
</head>
<body>
    <h1>Blogs</h1>
    <ul>
        {% for blog in blogs.items %} <!-- loop through the items for the current page -->
        <li>
            <h2>{{ blog.title }}</h2>
            <p>{{ blog.content }}</p>
        </li>
        {% endfor %}
    </ul>
    <ul>
        <!-- previous page -->
        {% if blogs.has_prev %}
        <li>
            <a href="{{ url_for('blogs', page=blogs.prev_num) }}">Previous</a>
        </li>
        {% endif %}
        <!-- all page numbers -->
        {% for page_num in blogs.iter_pages() %}
        {% if page_num %}
        {% if page_num != blogs.page %}
        <li>
            <a href="{{ url_for('blogs', page=page_num) }}">{{ page_num }}</a>
        </li>
        {% else %}
        <li class="active">
            <a href="#">{{ page_num }}</a>
        </li>
        {% endif %}
        {% else %}
        <li>
            <span class="ellipsis">…</span>
        </li>
        {% endif %}
        {% endfor %}
        <!-- next page -->
        {% if blogs.has_next %}
        <li>
            <a href="{{ url_for('blogs', page=blogs.next_num) }}">Next</a>
        </li>
        {% endif %}
    </ul>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

As you can see from the code and the output, we have successfully created a working template that displays our data in a paginated manner. We have also defined a nice model that represents our data in the database and allows us to query it easily. In addition, we have added some nice features to our templates, such as page numbers and previous and next buttons, that enable our users to navigate through our data and find what they are looking for.

And that's it! You have just learned how to create a working pagination for your data sets using Flask and Jinja2. πŸŽ‰ Isn't that awesome? 😎 Pagination is a great way to improve the user experience and performance of your web applications. πŸš€ You can now display your data in a neat and organized way, and let your users navigate through it with ease. πŸ™Œ I hope you enjoyed this tutorial and learned something new. 😊

Original post: https://pythonpat.com/article/pagination-with-flask-and-jinja2

Top comments (0)