Django爲此提供了模塊django.core.paginator
:https://docs.djangoproject.com/en/1.10/topics/pagination/。在Wagtail中使用它與Django文檔中的示例非常相似 - 唯一真正的區別是,當您設置要傳遞給模板的Paginator
對象時,可以使用頁面模型中的get_context
方法的視圖功能。您的模型定義將是這個樣子:
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
class ResourceIndexPage(Page):
# ...
def get_context(self, request):
context = super(ResourceIndexPage, self).get_context(request)
# Get the full unpaginated listing of resource pages as a queryset -
# replace this with your own query as appropriate
all_resources = ResourcePage.objects.live()
paginator = Paginator(all_resources, 5) # Show 5 resources per page
page = request.GET.get('page')
try:
resources = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
resources = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
resources = paginator.page(paginator.num_pages)
# make the variable 'resources' available on the template
context['resources'] = resources
return context
在您的模板,現在你可以使用{% for resource in resources %}
遍歷所有的項目,並顯示分頁鏈接如下:
<ul class="pagination">
{% if resources.has_previous %}
<li><a href="?page={{ resources.previous_page_number }}"><i class="fa fa-angle-left"></i></a></li>
{% endif %}
{% for page_num in resources.paginator.page_range %}
<li {% if page_num == resources.number %}class="active"{% endif %}><a href="?page={{ page_num }}">{{ page_num }}</a></li>
{% endfor %}
<li><a href="?page={{ resources.next_page_number }}"><i class="fa fa-angle-right"></i></a></li>
</ul>
只是想補充一點,我在最後一個'
'附近使用了以下內容,如果有下一個頁面只顯示下一個箭頭 - '{%if resources.has_next%} {%endif%}' – KimNice 。這工作得很好。有什麼方法可以更新這個,所以我可以使用有/ page/1/in的好網址嗎?目前我正在竊聽,但它非常混亂! – Designer023
@ Designer023查看'RoutablePageMixin':http://docs.wagtail.io/en/v1.13.1/reference/contrib/routablepage.html – gasman