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">&laquo;</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">&raquo;</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">&laquo;</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">&raquo;</span>

</a>

</li>

{% endif %}

</ul>

</nav>

</div>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM