How to Display Functional Pagination in Twig 3 Template

304 Views Asked by At

Objective is to add pagination using Twig 3 that displays and functions identically to the pagination used at the bottom of Stack Overflow question feeds:

Screenshot of Stack Overflow pagination

Researching this in other questions and in outside forums has only yielded results using depreciated twig functions, so asking here in case anyone has any insight on how to do this properly.

I have a twig template that currently displays pagination, but numerically lists and hyperlinks every page in the list without trimming and adding an ellipses the way Stack Overflow does (also it has no dynamic Next/Previous links). For some background, some of the parameter decisions are framed around the API that I'm working with and follows its documentation for HTTP requests to the JSON data. This template is functional but it's not practical from a user oriented design standpoint:

{% set pgonpage = 5 %}
  {% set pgofpages = (count/pgonpage) | round(0, 'ceil') %}
    <p>{% for i in 1..pgofpages %} 
    {% if i==urlparam.pg %} 
    (<strong>{{urlparam.pg}}</strong>)
  {% else %} 
    <a href=?pg={{i}}>{{i}}</a>
  {% endif %} 
{% endfor %}</p>

For brevity I removed part of the template above that loops the main content, but to clarify the {% set pgonpage = 5 %} tag sets the number of JSON data to be displayed on a given page, and is functional.

This is how the template URL looks:

{% set page = 1 %}
  {% if urlparam.pg > 0 %}
    {% set page = urlparam.pg %}
  {% endif %}
https://api.example.com?per_page=5&page={{page}}

This is the result if on https://actual.example.com?pg=1:

Screenshot of Pagination Resulting from Current Twig Template

0

There are 0 best solutions below