|
| 1 | +# Pagination |
| 2 | + |
| 3 | +The Django paginator API is impossible to fully recreate in YAML. Instead, we can define context in Python, with [context modifiers](../guides/defining-template-context.md#modifying-template-contexts-with-python). Take a template like: |
| 4 | + |
| 5 | +```jinja2 |
| 6 | +{% with count=search_results.paginator.count %} |
| 7 | + {{ count }} result{{ count|pluralize }} found. |
| 8 | +{% endwith %} |
| 9 | +
|
| 10 | +{% for result in search_results %} |
| 11 | + <h4>{{ result.title }}</h4> |
| 12 | +{% endfor %} |
| 13 | +
|
| 14 | +{% if search_results.paginator.num_pages > 1 %} |
| 15 | + <nav aria-label="Pagination"> |
| 16 | + <ul> |
| 17 | + {% if search_results.has_previous %} |
| 18 | + <li><a href="?page={{ search_results.previous_page_number }}{% if search_query %}&query={{ search_query|urlencode }}{% endif %}">previous</a></li> |
| 19 | + {% endif %} |
| 20 | +
|
| 21 | + <li>{{ search_results.number }}/{{ search_results.paginator.num_pages }}</li> |
| 22 | +
|
| 23 | + {% if search_results.has_next %} |
| 24 | + <li><a href="?page={{ search_results.next_page_number }}{% if search_query %}&query={{ search_query|urlencode }}{% endif %}">next</a></li> |
| 25 | + {% endif %} |
| 26 | + </ul> |
| 27 | + </nav> |
| 28 | +{% endif %} |
| 29 | +``` |
| 30 | + |
| 31 | +We can create the needed context by using Django’s [`Paginator` API](https://docs.djangoproject.com/en/3.2/topics/pagination/). |
| 32 | + |
| 33 | +```python |
| 34 | +from django.core.paginator import Paginator |
| 35 | + |
| 36 | +from pattern_library import register_context_modifier |
| 37 | + |
| 38 | + |
| 39 | +@register_context_modifier(template='patterns/pages/search/search.html') |
| 40 | +def replicate_pagination(context, request): |
| 41 | + object_list = context.pop('search_results', None) |
| 42 | + if object_list is None: |
| 43 | + return |
| 44 | + |
| 45 | + original_length = len(object_list) |
| 46 | + |
| 47 | + # add dummy items to force pagination |
| 48 | + for i in range(50): |
| 49 | + object_list.append(None) |
| 50 | + |
| 51 | + paginator = Paginator(object_list, original_length) |
| 52 | + context.update( |
| 53 | + paginator=paginator, |
| 54 | + search_results=paginator.page(10), |
| 55 | + is_paginated=True, |
| 56 | + object_list=object_list |
| 57 | + ) |
| 58 | +``` |
0 commit comments