Reputation: 263
I am having an issue figuring out my pagination for django. Following the docs everything works correctly if I am on the first page or the last page, but I have code duplicating. Everything I have tried I end up getting some sort of exception, mostly empty page exception. I understand that this is because my solutions involve not checking if page_obj.has_previous or .has_next. I am not sure how to solve this and any help would be greatly appreciated. I will attach a screen shot so you can see what I mean.
pagination:
<div class="pagination justify-content-center pt-3">
<nav aria-label='pagination'>
<ul class="pagination step-links">
{% if page_obj.has_previous %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.previous_page_number }}" aria-label='Previous'>
<span aria-hidden='true'>«</span>
</a>
</li>
<li class="page-item">
<a class='page-link'>
{{ page_obj.number }} of {{ page_obj.paginator.num_pages }}
</a>
</li>
{% endif %}
{% if page_obj.has_next %}
<li class="page-item">
<a class='page-link'>
{{ page_obj.number }} of {{ page_obj.paginator.num_pages }}
</a>
</li>
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.next_page_number }}" aria-label='Next'>
<span aria-hidden='true'> » </span>
</a>
</li>
{% endif %}
</ul>
</nav>
</div>
As you can see the '2 of 3' gets duplicated. I see exactly why it gets duplicated in my code but if I delete one of the list items then the {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}
will not be displayed on the first or last page. What would be the best way to solve this? I haven't been able to figure it out on my own
Upvotes: 0
Views: 83
Reputation: 176
The code (page-item class) just has to be outside the if block. This will work.
{% if page_obj.has_previous %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.previous_page_number }}" aria-label='Previous'>
<span aria-hidden='true'>«</span>
</a>
</li>
{% endif %}
<li class="page-item">
<a class='page-link'>
{{ page_obj.number }} of {{ page_obj.paginator.num_pages }}
</a>
</li>
{% if page_obj.has_next %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.next_page_number }}" aria-label='Next'>
<span aria-hidden='true'> » </span>
</a>
</li>
{% endif %}
Upvotes: 1