layui的分页是用js实现的,格式类似这样:
//执行一个laypage实例
laypage.render({
elem: 'test1' //注意,这里的 test1 是 ID,不用加 # 号
,count: 50 //数据总数,从服务端得到
,page: true,//开启分页
});
layui的分页虽然实现了样式,但是数据渲染部分要自己操作,但是原理并不难:前端传递当前页码和显示页数,后端根据这两个参数数据总量计算出取值区间,然后取到数据返回给前端渲染即可,代码实现如下:
1.layui利用request参数传递当前页码和显示页数
laypage.render({
elem: 'test1' //注意,这里的 test1 是 ID,不用加 # 号
,count: 50 //数据总数,从服务端得到
,page: true,//开启分页
,request: {
pageName: 'curr' //页码的参数名称,默认:page
,limitName: 'nums' //每页数据量的参数名,默认:limit
}
});
后端得到数据类似:
"GET /backend/getNodeList?curr=2&nums=10 HTTP/1.1"
2.后端处理返回数据
<1>可以用之前写的pager.py获取数据区间
pager.py
class Pagination(object):
def __init__(self, dataCount, currentPage=1, cowCount=10, perPageCount=10):
self.totalCount = dataCount
self.perPageCount=perPageCount
self.cowCount=cowCount
if currentPage <= 0:
self.currentPage=1
elif currentPage>self.max_page:
self.currentPage=self.max_page
else:
self.currentPage=currentPage
@property
def max_page(self):
a,b=divmod(self.totalCount,self.perPageCount)
if b==0:
return a
else:
return a+1
@property
def start_page(self):
# 1-10 2-11 3-12
# 1-7 2-8 3-9
# 假设当前页在中间,则有:
step=int(self.cowCount/2)
if self.currentPage<=step:
return 1
elif self.max_page-self.currentPage<step:
return self.max_page-self.cowCount+1
else:
return self.currentPage-step+1
@property
def end_page(self):
return self.start_page+self.cowCount-1
@property
# 模板语言的循环语句只有for in结构,只能返回列表供模板页面使用
def page_range(self):
return range(self.start_page, self.end_page+1)
@property
def next_page(self):
if self.currentPage<self.max_page:
return self.currentPage+1
else:
return "out"
@property
def prev_page(self):
if self.currentPage > 1:
return self.currentPage-1
else:
return "out"
def data_start(self):
return (self.currentPage-1)*self.perPageCount
def data_end(self):
return self.currentPage * self.perPageCount
<2>处理并返回数据渲染,最终view如下:
from tools.pager import *
def getNodeList(request):
currentPage=int(request.GET.get("curr"))
dataCount=int(Node.objects.all().count())
perPageCount=int(request.GET.get("nums"))
page_obj = Pagination(dataCount=dataCount, currentPage=currentPage, perPageCount=perPageCount)
data_start = page_obj.data_start()
data_end = page_obj.data_end()
nodelist={
"code": 0,
"msg": "",
"count": dataCount,
"data": []
}
node_obj=list(Node.objects.all()[data_start:data_end].values())
for item in node_obj:
if item["work_or_no"]=="1":
item["work_or_no"]="开"
else:
item["work_or_no"] = "关"
nodelist["data"]=node_obj
return HttpResponse(json.dumps(nodelist))
效果图: