Last active
March 12, 2025 21:25
-
-
Save maxpou/612359ed4af4cc5c4f06 to your computer and use it in GitHub Desktop.
Example of pagination with Twig
This file contains hidden or 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
{# | |
Parameters: | |
* nbPages (int): number of pages | |
* currentPage (int): current pages | |
* url (string): route name & query (string): route parameter | |
ex: list/page-5?q=myFilter (5 = page and query = myFilter) | |
#} | |
{% spaceless %} | |
{% if nbPages > 1 %} | |
{# Number of page around current page+1 #} | |
{% set nearbyPagesLimit = 4 %} | |
<div> | |
<ul class="pagination"> | |
{% if currentPage != 1 %} | |
<li> | |
<a href="{{ path(url, { 'page': 1, 'q': query }) }}">First</a> | |
</li> | |
{% endif %} | |
{% for i in 1..nbPages %} | |
{% if 0 == (currentPage - nearbyPagesLimit) - loop.index %} {# dot before #} | |
<li class="disabled"><a href="#">...</a></li> | |
{% elseif 0 == (currentPage + nearbyPagesLimit) - loop.index %} {# dot after #} | |
<li class="disabled"><a href="#">...</a></li> | |
{% elseif 0 < (currentPage - nearbyPagesLimit) - loop.index %} {# hide all before #} | |
{% elseif 0 > (currentPage + nearbyPagesLimit) - loop.index %} {# hide all after #} | |
{% else %} | |
<li {% if currentPage == loop.index %} class="active"{% endif %}> | |
<a href="{{ path(url, { 'page': loop.index, 'q': query }) }}">{{ loop.index }}</a> | |
</li> | |
{% endif %} | |
{% endfor %} | |
{% if currentPage != nbPages %} | |
<li> | |
<a href="{{ path(url, { 'page': nbPages, 'q': query }) }}">Last</a> | |
</li> | |
{% endif %} | |
</ul> | |
</div> | |
{% endif %} | |
{% endspaceless %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pagination with a variable.