Skip to content

Instantly share code, notes, and snippets.

@alexander-schranz
Last active September 18, 2016 13:21
Show Gist options
  • Select an option

  • Save alexander-schranz/93eecac6944e1aee526cb663a8283508 to your computer and use it in GitHub Desktop.

Select an option

Save alexander-schranz/93eecac6944e1aee526cb663a8283508 to your computer and use it in GitHub Desktop.
A twig include for rendering a pagination
{#- A twig html pagination with correct handling of many pages.
#
# arrows bool
# page int
# maxPage int
# limit int
-#}
{% if maxPage > 1 %}
<div class="pagination">
{% spaceless %}
{# create url #}
{% set queryString = (app.request.query.all()|merge({'page': '_page_'}))|url_encode %}
{% set currentUrl = app.request.pathInfo ~ '?' ~ queryString %}
{# limit shown paginations points #}
{% if limit is not defined %}
{% set limit = 2 %}
{% endif %}
{% set shownItems = limit * 2 - 1 %}
{# prev if exists #}
{% if arrows|default(true) and page > 1 %}
<a href="{{ currentUrl|replace({'_page_': page - 1 })|raw }}" rel="prev" class="prev">
&nbsp;
</a>
{% endif %}
{% for i in 1..maxPage %}
{# rel attribute #}
{% set rel = '' %}
{% if i == (page - 1) %}
{% set rel = 'prev' %}
{% elseif i == (page + 1) %}
{% set rel = 'next' %}
{% endif %}
{# only render when first last or inside the limitation #}
{% if
i == 1 or i == maxPage
or (i > (page - limit) and i < (page + limit))
or (page <= shownItems and i <= shownItems)
or (page > (maxPage - shownItems) and i > (maxPage - shownItems))
%}
{# link #}
<a {{ i == page ? 'class="active" ' : '' }}href="{{ currentUrl|replace({'_page_': i })|raw }}" {% if rel %}rel="{{ rel }}"{% endif %}>
{{ i }}
</a>
{% elseif i == 2 or i == (maxPage - 1) %}
<span>...</span>
{% endif %}
{% endfor %}
{# next if exists #}
{% if arrows|default(true) and page < maxPage %}
<a href="{{ currentUrl|replace({'_page_': page + 1 })|raw }}" rel="next" class="next">
&nbsp;
</a>
{% endif %}
{% endspaceless %}
</div>
{% endif %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment