我有一个小型Flask应用程序,可以呈现博客文章:
views.py:
class ListView(MethodView):
def get(self, page=1):
posts = Post.objects.all()
return render_template('posts/list.html', posts=posts)
这一切都很好,但我想为posts
对象添加分页。看project docs,我看到有一个分页课。
所以我尝试了这个:
class ListView(MethodView):
def get(self, page=1):
posts = Post.objects.paginate(page=page, per_page=10)
return render_template('posts/list.html', posts=posts)
但现在我收到了一个错误:
TypeError: 'Pagination' object is not iterable
那么如何在模板中迭代我的posts
?
任何帮助都非常感激。
答案 0 :(得分:9)
Pagination
对象有items
list,其中包含mongoengine文档对象(在您的情况下为Post
个对象)。可以迭代此列表以显示文档。
例如,在您的模板中:
{% for post in posts.items %}
{{ post.title }}
{{ post.content }}
{% endfor %}
要获取分页链接的实际页码,请使用iter_pages()
:
<div id="pagination-links">
{% for page in posts.iter_pages() %}
{{ page }}
{% endfor %}
</div>
documentation和github link above都有更好的分页链接示例:
{% macro render_pagination(pagination, endpoint) %}
<div class=pagination>
{%- for page in pagination.iter_pages() %}
{% if page %}
{% if page != pagination.page %}
<a href="{{ url_for(endpoint, page=page) }}">{{ page }}</a>
{% else %}
<strong>{{ page }}</strong>
{% endif %}
{% else %}
<span class=ellipsis>…</span>
{% endif %}
{%- endfor %}
</div>
{% endmacro %}