django实现web分页的三种方法
先看一下这三种方法的效果图
方案一,可以简单的完成上下页,当前页的显示
<div class="pagination">
<span class="step-links">
{% if customer_list.has_previous %}
<a href="?page={{customer_list.previous_page_number}}">previous</a>
{% endif %}
<span class="current">
Page {{ customer_list.number }} of {{ customer_list.paginator.num_pages }},
</span>
{% if customer_list.has_next %}
<a href="?page={{customer_list.next_page_number}}">next</a>
{% endif %}
</span>
</div>
方案二,可以将所有的页码漂亮的显示,以及上下页功能
<div class="pagination">
<nav>
<ul class="pagination">
{% if customer_list.has_previous %}
<li class="">
<a href="?page={{ customer_list.previous_page_number }}" aria-label="Previous">
<span aria_hidden="true">«</span>
</a>
</li>
{% endif %}
{% for page_num in customer_list.paginator.page_range %}
{% guess_page customer_list.number page_num %}
{% if page_num == customer_list.number %}
<li class="active"><a href="?page={{ page_num }}">{{page_num}}</a> </li>
{% else %}
<li class=""><a href="?page={{ page_num }}">{{page_num}}</a> </li>
{% endif %}
{% endfor %}
{% if customer_list.has_next %}
<li class="">
<a href="?page={{ customer_list.next_page_number }}" aria-label="Next">
<span aria_hidden="true">»</span>
</a>
</li>
{% endif %}
</ul>
</nav>
</div>
方案三,动态的显示当前页附近的几页,以及上下页功能
采用templat tags的方法:
新建tags,如目录:
template tags的写法
custom_tags.py:
from django import template
from django.utils.html import format_html
register = template.Library() #注册到django的语法库
@register.simple_tag
def guess_page(current_page,loop_num):
offset = abs(current_page-loop_num)
if offset < 3:
if current_page == loop_num:
page_ele = '''<li class="active"><a href="?page=%s">%s</a> </li>'''%(loop_num,loop_num)
else:
page_ele = '''<li class=""><a href="?page=%s">%s</a> </li>'''%(loop_num,loop_num)
return format_html(page_ele)
else:
return ''
前端的写法
<div class="pagination">
<nav>
<ul class="pagination">
{% if customer_list.has_previous %}
<li class="">
<a href="?page={{ customer_list.previous_page_number }}" aria-label="Previous">
<span aria_hidden="true">«</span>
</a>
</li>
{% endif %}
{% for page_num in customer_list.paginator.page_range %}
{% guess_page customer_list.number page_num %}
{% endfor %}
{% if customer_list.has_next %}
<li class="">
<a href="?page={{ customer_list.next_page_number }}" aria-label="Next">
<span aria_hidden="true">»</span>
</a>
</li>
{% endif %}
</ul>
</nav>
</div>