效果演示:
 
github地址:https://github.com/mncu/django_projects/tree/master/django_projects/pagination_test

本例中總頁數為30頁,顯示頁數為12頁,當前頁的前排頁數為4,后排頁數為5
將分頁分為三種情況:
1 當前頁為第1頁到第7頁的時候,無省略頁,且12個位置的內容是不變
2 當前頁為第8頁到第25頁時,位置1與位置2內容不變,當前頁一直處于位置7,
3 當前頁為第25頁到第30頁時,位置1與位置2內容不變,位置8到位置12的內容不變,當前頁在位置8到位置12之中變換
自定義標簽代碼:
from django import templateregister = template.Library()@register.assignment_tagdef pagination(current_page,paginator,num_of_displaypages=10,num_of_backpages=4): # current_page is a django.core.paginator.Page 's instance # paginator is a django.core.paginator.Paginator 's instance # num_of_frontpages = num_of_displaypages - num_of_backpages -3 html='' # 當總頁數小于等于 顯示頁數 時,則將總頁數全部顯示 if paginator.num_pages <= num_of_displaypages : for i in range(1,paginator.num_pages+1): html+= '<li ><a href="?page=%s" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >%s </a></li>'%(i,i) return html # 第一種情況 elif current_page.number <= num_of_displaypages-num_of_backpages: for i in range(1,num_of_displaypages+1): html+= '<li ><a href="?page=%s" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >%s </a></li>'%(i,i) return html # 第二種情況 elif num_of_displaypages-num_of_frontpages <= current_page.number <= paginator.num_pages-num_of_backpages : html = ''' <li><a href="?page=1" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >1</a></la> <li class="disabled"><a href="?page=1" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >...</a></la> ''' for i in range(current_page.number-num_of_frontpages,current_page.number+num_of_backpages+1): html+='<li><a href="?page=%s" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >%s</a></la>'%(i,i) return html # 第三種情況 else: html = ''' <li><a href="?page=1" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >1</a></la> <li class="disabled"><a href="?page=1" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >...</a></la> ''' for i in range(paginator.num_pages-num_of_backpages-num_of_frontpages,paginator.num_pages+1): html+='<li><a href="?page=%s" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >%s</a></la>'%(i,i) return html
新聞熱點
疑難解答