背景:我正在开发一个博客,核心的两个model是文章和文章类别。
现在想要实现的功能是:点击一个文章类别,以分页的形式显示这个文章类别下的所有文章,类似这种效果。
参考的书中分页宏只接受页数这一个参数,经过尝试,成功给分页宏添加了文章类别参数,实现了上述功能。
posts.html
{% extends "public/base.html" %}
{% import "public/macros.html" as macros %}{% block content %}<div class="row" style="margin-top: 20px;"><div class="col-sm-4">{% include "public/categories.html" %}</div>{% if posts %}<div class="col-sm-8">{% include "public/_posts.html" %}<div style="text-align: center; margin-top: 20px;">{% if category %}{{ macros.pagination_widget(pagination, '.posts', category.id) }}{% else %}{{ macros.pagination_widget(pagination, '.posts', 0) }}{% endif %}</div></div>{% endif %}</div>
{% endblock %}
关键代码
macros.html
{% macro pagination_widget(pagination, endpoint, category_id) %}<ul class="pagination justify-content-center"><li {% if not pagination.has_prev %} class="page-item disabled" {% else %} class="page-item" {% endif %}><a class="page-link" href="{% if pagination.has_prev %}{{ url_for(endpoint,page = pagination.page - 1, category_id = category_id, **kwargs) }}{% else %}#{% endif %}">Previous</a></li>{% for p in pagination.iter_pages() %}{% if p %}{% if p == pagination.page %}<li class="page-item active"><a class="page-link" href="{{ url_for(endpoint, page = p, category_id = category_id, **kwargs) }}">{{ p }}</a></li>{% else %}<li class="page-item"><a class="page-link" href="{{ url_for(endpoint, page = p, category_id = category_id, **kwargs) }}">{{ p }}</a></li>{% endif %}{% else %}<li class="page-item disabled"><a class="page-link" href="#">…</a></li>{% endif %}{% endfor %}<li {% if not pagination.has_next %} class="disabled page-item" {% else %} class="page-item"{% endif %}><a class="page-link" href="{% if pagination.has_next %}{{ url_for(endpoint,page = pagination.page + 1, category_id = category_id, **kwargs) }}{% else %}#{% endif %}">Next</a></li></ul>
{% endmacro %}
关键代码
routes.py
@app.route('/posts', methods=['GET', 'POST'])
@app.route('/posts/<int:category_id>', methods=['GET', 'POST'])
def posts(category_id=0):page = request.args.get('page', 1, type=int)if 0 != category_id:category = Category.query.get_or_404(category_id)pagination = Post.query.with_parent(category).order_by(Post.timestamp.desc()).paginate(page=page, per_page=10)else:category = Nonepagination = Post.query.order_by(Post.timestamp.desc()).paginate(page=page, per_page=10)posts = pagination.itemscategories = Category.query.all()return render_template('public/posts.html', posts=posts, pagination=pagination, categories=categories, category=category)
关键代码