Last active
February 11, 2021 23:01
-
-
Save wonderb0lt/10645080 to your computer and use it in GitHub Desktop.
Very basic MongoEngine pagination
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from math import ceil | |
class Pagination: | |
def __init__(self, items, page, per_page, total_items): | |
self.items = items | |
self.page = page | |
self.total_items = total_items | |
self.per_page = per_page | |
self.num_pages = int(ceil(total_items / float(per_page))) | |
@property | |
def has_next(self): | |
return self.page < self.num_pages | |
@property | |
def has_prev(self): | |
return self.page > 1 | |
@property | |
def next_page(self): | |
return self.page + 1 | |
@property | |
def prev_page(self): | |
return self.page - 1 | |
def paginate(queryset, page=1, per_page=30): | |
skip = (page-1)*per_page | |
limit = per_page | |
return Pagination(queryset.limit(limit).skip(skip), page=page, per_page=per_page, | |
total_items=queryset.count()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{# Jinja2 macro #} | |
{% macro paginate(pagination, destination, small=False) %} | |
{% if pagination.num_pages > 1 %} | |
<ul class="pagination {% if small %}pagination-sm{% endif %}" id="pagination"> | |
<li {% if not pagination.has_prev %}class="disabled"{% endif %}> | |
<a href="{{ url_for(destination) }}?page={{ pagination.prev_page }}">«</a> | |
</li> | |
{% for i in range(1, pagination.num_pages) %} | |
<li {% if products.page == i %}class="active"{% endif %}> | |
<a href="{{ url_for(destination) }}?page={{ i }}">{{ i }}</a> | |
</li> | |
{% endfor %} | |
<li {% if not pagination.has_next %}class="disabled"{% endif %}> | |
<a href="{{ url_for(destination) }}?page={{ pagination.next_page }}">»</a> | |
</li> | |
</ul> | |
{% endif %} | |
{% endmacro %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this. I was struggling to figure out how to do this. Also works with Flask-PyMongo...