Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@devnix
Forked from maxpou/_pagination.html.twig
Last active May 29, 2019 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devnix/c927bfd64084e7a592f7aeda436ac4be to your computer and use it in GitHub Desktop.
Save devnix/c927bfd64084e7a592f7aeda436ac4be to your computer and use it in GitHub Desktop.
Example of pagination with Twig
{#
Parameters:
* total (int): number of pages
* current (int): current pages
* url (string): route name & query (string): route parameter
ex: list/page-5?q=myFilter (5 = page and query = myFilter)
* nearbyPagesLimit (int) optional: limit of pages around the current page
#}
{% macro pagination(total, current, url, nearbyPagesLimit = 4) %}
{% spaceless %}
{% if total > 1 %}
<ul class="pagination">
{% for i in 1..total %}
{% if 0 == (current - nearbyPagesLimit) - loop.index %}
<li><a href="{{ (url ~ 1)|e }}">1</a></li>
{% if 1 != loop.index %}
<li><span>…</span></li>
{% endif %}
{% elseif 0 == (current + nearbyPagesLimit) - loop.index and (current + nearbyPagesLimit) < total %}
<li><span>…</span></li>
{% elseif 0 < (current - nearbyPagesLimit) - loop.index %}
{% elseif 0 > (current + nearbyPagesLimit) - loop.index %}
{% else %}
<li {{ current == loop.index ? 'class="active"' }}>
{% if current == loop.index %}
<span>{{ loop.index }}</span>
{% else %}
<a href="{{ url ~ loop.index }}">{{ loop.index }}</a>
{% endif %}
</li>
{% endif %}
{% endfor %}
{% if current != total and (current + nearbyPagesLimit) < total %}
<li><a href="{{ (url ~ total)|e }}">{{ total }}</a></li>
{% endif %}
</ul>
{% endif %}
{% endspaceless %}
{% endmacro %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment