背景:我正在开发一个博客,核心的两个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 = None
pagination = Post.query.order_by(Post.timestamp.desc()).paginate(page=page, per_page=10)
posts = pagination.items
categories = Category.query.all()
return render_template('public/posts.html', posts=posts, pagination=pagination, categories=categories, category=category)
关键代码文章来源:https://www.toymoban.com/news/detail-812097.html
文章来源地址https://www.toymoban.com/news/detail-812097.html
到了这里,关于flask分页宏增加更多参数的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!