From 8e63ba89db137e7980ddc7fd77aea837437b8545 Mon Sep 17 00:00:00 2001 From: Neo Date: Mon, 9 Sep 2024 23:07:10 +0000 Subject: [PATCH] Add pagination to blog posts Implemented pagination in the blog to display 3 posts per page. This change allows users to navigate through posts using a pagination control at the bottom of the page. The pagination follows the pattern: << < 1 2 3 ... n > >>, enabling navigation to the first, previous, specific, next, or last pages. This improves user experience by preventing long scrolls on pages with many posts. Issue ID: FLAS-33 --- flaskr/blog.py | 11 ++++++++++- flaskr/templates/blog/index.html | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/flaskr/blog.py b/flaskr/blog.py index d086da6b..668f6d70 100644 --- a/flaskr/blog.py +++ b/flaskr/blog.py @@ -7,6 +7,7 @@ from flask import request from flask import url_for from werkzeug.exceptions import abort import markdown +import math from .auth import login_required from .db import get_db @@ -18,16 +19,24 @@ bp = Blueprint("blog", __name__) def index(): """Show all the posts, most recent first.""" db = get_db() + page = request.args.get('page', 1, type=int) + per_page = 3 + total_posts = db.execute("SELECT COUNT(*) FROM post").fetchone()[0] + total_pages = math.ceil(total_posts / per_page) + posts = db.execute( "SELECT p.id, title, body, created, author_id, username" " FROM post p JOIN user u ON p.author_id = u.id" " ORDER BY created DESC" + " LIMIT ? OFFSET ?", + (per_page, (page - 1) * per_page) ).fetchall() + # Convert markdown to HTML for each post body posts = [ {**post, 'body': markdown.markdown(post['body'])} for post in posts ] - return render_template("blog/index.html", posts=posts) + return render_template("blog/index.html", posts=posts, page=page, total_pages=total_pages) def get_post(id, check_author=True): diff --git a/flaskr/templates/blog/index.html b/flaskr/templates/blog/index.html index 3e666de2..864c3f3c 100644 --- a/flaskr/templates/blog/index.html +++ b/flaskr/templates/blog/index.html @@ -25,5 +25,24 @@
{% endif %} {% endfor %} + + + {% endblock %}