From 6298b1228a7313de4375a567d79a7ab046bc2a26 Mon Sep 17 00:00:00 2001 From: Kevin Morris Date: Wed, 15 Sep 2021 11:31:55 -0700 Subject: [PATCH] feat(FastAPI): add templates/partials/widgets/pager.html A pager that can be used for paginated result tables. Signed-off-by: Kevin Morris --- aurweb/filters.py | 50 +++++++++++++++++++++++++++ templates/partials/widgets/pager.html | 26 ++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 aurweb/filters.py create mode 100644 templates/partials/widgets/pager.html diff --git a/aurweb/filters.py b/aurweb/filters.py new file mode 100644 index 00000000..bb56c656 --- /dev/null +++ b/aurweb/filters.py @@ -0,0 +1,50 @@ +from typing import Any, Dict + +import paginate + +from jinja2 import pass_context + +from aurweb import util +from aurweb.templates import register_filter + + +@register_filter("pager_nav") +@pass_context +def pager_nav(context: Dict[str, Any], + page: int, total: int, prefix: str) -> str: + page = int(page) # Make sure this is an int. + + pp = context.get("PP", 50) + + # Setup a local query string dict, optionally passed by caller. + q = context.get("q", dict()) + + search_by = context.get("SeB", None) + if search_by: + q["SeB"] = search_by + + sort_by = context.get("SB", None) + if sort_by: + q["SB"] = sort_by + + def create_url(page: int): + nonlocal q + offset = max(page * pp - pp, 0) + qs = util.to_qs(util.extend_query(q, ["O", offset])) + return f"{prefix}?{qs}" + + # Use the paginate module to produce our linkage. + pager = paginate.Page([], page=page + 1, + items_per_page=pp, + item_count=total, + url_maker=create_url) + + return pager.pager( + link_attr={"class": "page"}, + curpage_attr={"class": "page"}, + separator=" ", + format="$link_first $link_previous ~5~ $link_next $link_last", + symbol_first="« First", + symbol_previous="‹ Previous", + symbol_next="Next ›", + symbol_last="Last »") diff --git a/templates/partials/widgets/pager.html b/templates/partials/widgets/pager.html new file mode 100644 index 00000000..4809accf --- /dev/null +++ b/templates/partials/widgets/pager.html @@ -0,0 +1,26 @@ +{# A pager widget that can be used for navigation of a number of results. + +Inputs required: + + prefix: Request URI prefix used to produce navigation offsets + singular: Singular sentence to be translated via tn + plural: Plural sentence to be translated via tn + PP: The number of results per page + O: The current offset value + total: The total number of results +#} + +{% set page = ((O / PP) | int) %} +{% set pages = ((total / PP) | ceil) %} + +
+

+ {{ total | tn(singular, plural) | format(total) }} + {{ "Page %d of %d." | tr | format(page + 1, pages) }} +

+ {% if pages > 1 %} +

+ {{ page | pager_nav(total, prefix) | safe }} +

+ {% endif %} +