Display only some of the page numbers by django pagination

前端 未结 8 1233
盖世英雄少女心
盖世英雄少女心 2020-12-07 10:34

I am using the django paginator in the template. Its working ok, but not good when there\'s large numbers of pages.

views.py:

def blog(request):
             


        
8条回答
  •  时光取名叫无心
    2020-12-07 11:08

    I found the simplest thing to do was to create a pagination snippet that just shows the pages you want it to.

    In my case I didn't want any previous or next links. I just wanted to always have a link to the first and last pages and then have the current page and the two pages either side of the current page.

    My template snippet (uses variables from django-tables2 - variables will have slightly different names if you're using a Django Paginator directly)

    {% load django_tables2 %}
    {% load humanize %}
    {% load i18n %}
    
    {% if table.page %}
      {% with table.page.paginator.count as total %}
        {% with table.page.number as page_num %}
          {% with table.page.paginator.num_pages as num_pages %}
            {% block pagination %}
              
    {% if table.paginator.num_pages > 1 %}
      {% for n in table.page.paginator.page_range %} {% if table.page.number|add:'-3' == n %} {# First page #}
    • 1
    • {% if n != 1 %}
    • {% endif %} {% elif table.page.number == n %} {# Current page #}
    • {{ n }}
    • {% elif table.page.number|add:'-3' < n and n < table.page.number|add:'3' %} {# Pages around current page #}
    • {{ n }}
    • {% elif table.page.number|add:'3' == n %} {# Last page #} {% if n != num_pages %}
    • {% endif %}
    • {{ num_pages }}
    • {% endif %} {% endfor %}
    {% endif %}
    {% endblock pagination %} {% endwith %} {% endwith %} {% endwith %} {% endif %}

    Examples of what my pagination looks like at different pages

    Credit: this was inspired by @Pavel1114's answer.

提交回复
热议问题