Skip to content

Instantly share code, notes, and snippets.

@Wilfred
Created July 8, 2013 15:41
Show Gist options
  • Select an option

  • Save Wilfred/5949946 to your computer and use it in GitHub Desktop.

Select an option

Save Wilfred/5949946 to your computer and use it in GitHub Desktop.
digg-style pagination with Django templates, e.g. "... 3 4 5 *6* 7 8 9 ..." and Twitter bootstrap
from django import template
"""It's sometimes really handy to be able to do basic arithmetic in
Django templates.
"""
register = template.Library()
@register.filter
def subtract(value, arg):
return value - arg
@register.filter
def add(value, arg):
return value + arg
<div class="pagination">
<ul>
<li {% if not table.page.has_previous %}class="disabled"{% endif %}>
<a href="{% querystring table.prefixed_page_field=table.page.previous_page_number %}">&laquo;</a>
</li>
{% with active_page=table.page.number %}
{% for page_number in table.paginator.page_range %}
{# if we're beyond the first five pages, just show "..." until three pages before the current page #}
{# e.g. on page 12 show: "... 9 10 11 12" #}
{% if active_page > 5 and page_number < active_page|subtract:4 %}
{# nothing to show #}
{% elif active_page > 5 and page_number == active_page|subtract:4 %}
{# show '...' #}
<li class="disabled">
<a href="#">...</a>
</li>
{# if we're before the last five pages, just show "..." for pages more than three after the current page #}
{# e.g. on page 1 of 10 show: "1 2 3 4 ..." #}
{% elif active_page < table.paginator.num_pages|subtract:5 and page_number > active_page|add:4 %}
{# nothing to show #}
{% elif active_page < table.paginator.num_pages|subtract:5 and page_number == active_page|add:4 %}
{# show '...' #}
<li class="disabled">
<a href="#">...</a>
</li>
{% else %}
{# show the page number as normal #}
<li {% if page_number == active_page %}class="active"{% endif %} foo="3">
<a href="{% querystring table.prefixed_page_field=page_number %}">{{ page_number }}</a>
</li>
{% endif %}
{% endfor %}
{% endwith %}
<li {% if not table.page.has_next %}class="disabled"{% endif %}>
<a href="{% querystring table.prefixed_page_field=table.page.next_page_number %}">&raquo;</a>
</li>
</ul>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment