Skip to content

Instantly share code, notes, and snippets.

@juban juban/index.twig
Last active Sep 6, 2019

Embed
What would you like to do?
Paginate any array within Craft CMS templates
{% set someArrayToPaginate = [
{someProperty:"One"},
{someProperty:"Two"},
{someProperty:"Three"},
{someProperty:"Four"},
{someProperty:"Five"},
{someProperty:"Six"},
{someProperty:"Seven"},
{someProperty:"Eight"},
{someProperty:"Nine"},
{someProperty:"Ten"},
{someProperty:"Eleven"},
{someProperty:"Twelve"}
] %}
{% set resultsDataProvider = create({'class': 'yii\\data\\ArrayDataProvider', 'allModels':someArrayToPaginate, 'pagination': {'pageSize': 10}}) %} {# adjust pageSize to the expected number of items per page #}
{% set results = resultsDataProvider.getModels() %}
{% set currentPage = resultsDataProvider.getPagination().getPage() + 1 %}
{% set pageCount = resultsDataProvider.getPagination().getPageCount() %}
{% if currentPage > 1 %}
{% set prevPage = currentPage - 1 %}
{% endif %}
{% if currentPage < pageCount %}
{% set nextPage = currentPage + 1 %}
{% endif %}
{% block content %}
{% if results|length %}
{% for result in results %}
<p>{{ result.someProperty }}</p>
{% endfor %}
{% if prevPage is defined %}<a href="{{ url(craft.request.url, {'page': prevPage}) }}">Previous Page</a>{% endif %}
{% if nextPage is defined %}<a href="{{ url(craft.request.url, {'page': nextPage}) }}">Next Page</a>{% endif %}
{% endif %}
{% endblock %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.