Skip to content

Instantly share code, notes, and snippets.

@cole007
Last active October 12, 2016 13:23
Show Gist options
  • Save cole007/bcb053849ec74ae2798be939fb4be463 to your computer and use it in GitHub Desktop.
Save cole007/bcb053849ec74ae2798be939fb4be463 to your computer and use it in GitHub Desktop.
Craft simple pagination macro
{% set q = craft.request.getParam('q') %}
{% set limit = 20 %}
{% for item in filtered|slice((q * limit),limit) %}
<p>{{ item.title }}</p>
{% endfor %}
{{ _self.paginate(filtered, q, limit) }}

Assumes showing five pages at a time. filtered is the instances you want to paginate, q is page number and limit is the number per page you want to show in your results.

{% macro paginate(items, q, limit) %}
{# contents of the macro here #}
{% set t = (items|length/20)|round(0,'floor') %}
{% if t > 1 %}
<ul role="navigation">
{% set floor = (q - 2) < 0 ? 0 : q - 2 %}
{% set ceil = (q + 2) > t ? t : q + 2 %}
{% set ceil = floor == 0 ? floor + 5 : ceil %}
{% set ceil = ceil > t ? t : ceil %}
{% set floor = ceil == t ? ceil - 5 : floor %}
{% set floor = floor < 0 ? 0 : floor %}
{% set url = url(craft.request.path) ~ '?pp=' %}
{% if floor > 0 %}
<li class="first"><a href="{{ url ~ 0 }}">First</a></li>
<li class="prev"><a href="{{ url ~ (q-1) }}"></a></li>
{% endif %}
{% if floor > 0 %}
<li>…</li>
{% endif %}
{% for i in (floor..ceil) %}
<li class="{% if i == q %} active{% endif %}"><a href="{{ url ~ i }}">{{ i+1 }}</a></li>
{% endfor %}
{% if ceil < t %}
<li>…</li>
<li class="next"><a href="{{ url ~ (q+1) }}"></a></li>
<li class="last"><a href="{{ url ~ t }}">Last</a></li>
{% endif %}
</ul>
{% endif %}
{% endmacro %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment