核心:
<a href=‘http://127.0.0.1:8000/index-%s‘>%s<a>
自定义分页
1.前端处理字符
后端的字符 return render(request,"index.html",{"l传到前端的数据":list})
{{ 传到前端的数据 | safe}}
2.后端处理字符
导入处理的模块 from django.utils.safestring import mark_safe mark_safe(需要处理的数据) 再传递到前端。 以下是练习的代码:前端:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> #on_c{ background-color: blueviolet; color: azure; } </style> </head> <body> <div> <ur> {% for i in list_info %} <li> <a >{{ i }}</a> </li> {% endfor %} </ur> <div style="width: 360px"> {#方式一,前端处理#} {#<a href="‘http://127.0.0.1:8000/index-%s‘">上一页</a>#} <span>{{ d2_s | safe}}</span> {% for i2 in d %} <span>{{ i2| safe}}</span> {% endfor %} <span>{{ d3_x |safe}}</span> {#方式二,后台处理数据#} {#<span>{{ d }}</span>#} </div> </div> </body> </html>
url配置:
urlpatterns = [ path(‘admin/‘, admin.site.urls), url(‘^index-(\d+)/‘, views.index), ]
views:
from django.shortcuts import render from django.shortcuts import HttpResponse from django.utils.safestring import mark_safe list_info = [] for i in range(1,199): list_info.append(i) def index(request,num1): #将str转为int num = int(num1) #每页显示多少数据 a = (num-1)*10 b = num*10 list_info2 = list_info[a:b] #分页长度,默认为10 e,f = divmod(len(list_info), 10) if f !=0: c = e+2 else: c = e+1 #分页跳转 d=[] for i in range(1,c): if i == num: d.append("<a id=‘on_c‘ href=‘http://127.0.0.1:8000/index-%s‘>%s<a>"%(i,i)) else: d.append("<a href=‘http://127.0.0.1:8000/index-%s‘>%s<a>" % (i, i)) #分页 str 数据处理 #方式一,前端处理 #方式二,后端处理 # d2 = mark_safe(d) #选中页面分页 居中 if num > 5: d2 = d[num-6:num+5] elif num <= 5: d2 = d[0:10] #上下翻页 if 1< num < len(d): d2_s = "<a href=‘http://127.0.0.1:8000/index-%s‘>上一页<a>" % (num-1) d3_x = "<a href=‘http://127.0.0.1:8000/index-%s‘>下一页<a>" % (num+1) elif num==1: d2_s = "<a href=‘http://127.0.0.1:8000/index-%s‘>上一页<a>" % num d3_x = "<a href=‘http://127.0.0.1:8000/index-%s‘>下一页<a>" % (num + 1) elif num==len(d): d2_s = "<a href=‘http://127.0.0.1:8000/index-%s‘>上一页<a>" % (num-1) d3_x = "<a href=‘http://127.0.0.1:8000/index-%s‘>下一页<a>" % num #将数值传递至前端 return render(request,"index.html",{"list_info":list_info2,‘d‘:d2,"d2_s":d2_s,"d3_x":d3_x})
原文地址:https://www.cnblogs.com/Anec/p/9579015.html
时间: 2024-11-10 01:11:48