网站首页 文章专栏 优雅地使用django进行分页(自定义tag)
优雅地使用django进行分页(自定义tag)
创建于:2018-10-01 16:00:00 更新于:2024-04-25 21:18:20 羽瀚尘 3032
django 干货,网站,django,分页,后端

{% raw %}

背景

使用django自带的 官方的分页器做了一个网站,但是分页的效果过于丑陋。只能展示上一页、下一页、总页数、当前页码。 而大多数的网站,基本都可以一次显示当前页码的临近页码,以及直接跳转到首页、末页、指定页。

下面是一个理想的分页器。 分页器效果

使用自定义tag实现分页器

其实使用JavaScript实现一个优雅的分页器并没有技术难度,只是繁琐的东西太多,尤其是当前页在最左边或者最右边时。使用一个开源的实现能减少工作量。我在这篇博客里找到了一个理想的分页器。

这篇博客使用到了自定义的tag, 可能需要看下官方教程

自定义tag使用要点: 1. 使用templatetags文件夹,与view.py同级(templatetags中要有__init__.py) 2. 将view.py的父文件夹放入setting.py中的INSTALLED_APP中 3. 使用 {% load proper_paginate %} 对自己的tag进行加载.注意这里应该加花括号与百分号。 3. 重启django

对原始分页器的修改

在使用中发现工作不正常,源码中{% for i in paginator|proper_paginate:page_obj.number %}出错, 可能是django版本不同造成的。我采用下述方案予以规避。

{% with temp=articles.paginator|proper_paginate:articles.number %}
{% for i in temp %}

使用with语句在模板中定义变量,可以参考在模板中定义变量

修改后的完整的html模板如下:

{% load proper_paginate %}
{% load url_replace %}
<ul class="pagination">
    {% if articles.number == 1 %}
        <li class="disabled"><span></span></li>
    {% else %}
        <li><a class="page-link" href="?{% url_replace request 'page' 1 %}"></a></li>
    {% endif %}
    {% if articles.has_previous %}
        <li><a class="page-link" href="?{% url_replace request 'page' articles.previous_page_number %}">«</a></li>
    {% else %}
        <li class="disabled"><span>«</span></li>
    {% endif %}
    {% with temp=articles.paginator|proper_paginate:articles.number %}
    {% for i in temp %}
        {% if articles.number == i %}
            <li class="active"><span> i }} <span class="sr-only">(current)</span></span></li>
        {% else %}
            <li><a class="page-link" href="?{% url_replace request 'page' i %}"> i }}</a></li>
        {% endif %}
    {% endfor %}
    {% endwith %}
    {% if articles.has_next %}
        <li><a class="page-link" href="?{% url_replace request 'page' articles.next_page_number %}">»</a></li>
    {% else %}
        <li class="disabled"><span>»</span></li>
    {% endif %}
    {% if articles.number == articles.num_pages %}
        <li class="disabled"><span></span></li>
    {% else %}
        <li><a class="page-link" href="?{% url_replace request 'page' articles.paginator.num_pages %}"></a></li>
    {% endif %}
</ul>

其他未解决问题: 1. 在{% with temp=articles.paginator|proper_paginate:articles.number %}中, proper_paginate至少需要2个变量,那三个变量怎么办?

{% endraw %}