后台实现的一个分页类:
1 from django.utils.safestring import mark_safe 2 3 4 class Page: 5 def __init__(self, current_page, data_count, per_page_count=10, pager_num=7): 6 self.current_page = current_page 7 self.data_count = data_count 8 self.per_page_count = per_page_count 9 self.pager_num = pager_num 10 11 @property 12 def start(self): 13 return (self.current_page - 1) * self.per_page_count 14 15 @property 16 def end(self): 17 return self.current_page * self.per_page_count 18 19 @property 20 def total_count(self): 21 v, y = divmod(self.data_count, self.per_page_count) 22 if y: 23 v += 1 24 return v 25 26 def page_str(self, base_url): 27 page_list = [] 28 29 if self.total_count < self.pager_num: 30 start_index = 1 31 end_index = self.total_count + 1 32 else: 33 if self.current_page <= (self.pager_num + 1) / 2: 34 start_index = 1 35 end_index = self.pager_num + 1 36 else: 37 start_index = self.current_page - (self.pager_num - 1) / 2 38 end_index = self.current_page + (self.pager_num + 1) / 2 39 if (self.current_page + (self.pager_num - 1) / 2) > self.total_count: 40 end_index = self.total_count + 1 41 start_index = self.total_count - self.pager_num + 1 42 43 if self.current_page == 1: 44 prev = ‘<a class="page" href="javascript:void(0);">上一页</a>‘ 45 else: 46 prev = ‘<a class="page" href="%s?p=%s">上一页</a>‘ % (base_url, self.current_page - 1,) 47 page_list.append(prev) 48 49 for i in range(int(start_index), int(end_index)): 50 if i == self.current_page: 51 temp = ‘<a class="page active" href="%s?p=%s">%s</a>‘ % (base_url, i, i) 52 else: 53 temp = ‘<a class="page" href="%s?p=%s">%s</a>‘ % (base_url, i, i) 54 page_list.append(temp) 55 56 if self.current_page == self.total_count: 57 nex = ‘<a class="page" href="javascript:void(0);">下一页</a>‘ 58 else: 59 nex = ‘<a class="page" href="%s?p=%s">下一页</a>‘ % (base_url, self.current_page + 1,) 60 page_list.append(nex) 61 62 jump = """ 63 <input type=‘text‘ /><a onclick=‘jumpTo(this, "%s?p=");‘>GO</a> 64 <script> 65 function jumpTo(ths,base){ 66 var val = ths.previousSibling.value; 67 location.href = base + val; 68 } 69 </script> 70 """ % (base_url,) 71 72 page_list.append(jump) 73 74 page_str = mark_safe("".join(page_list)) 75 76 return page_str
原文地址:https://www.cnblogs.com/WSX1994/p/9135758.html
时间: 2024-10-23 15:09:41