Skip to content

Instantly share code, notes, and snippets.

@juban juban/index.twig
Last active May 31, 2020

Embed
What would you like to do?
Paginate any array within Craft CMS 3 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 %}
@JamesNock

This comment has been minimized.

Copy link

JamesNock commented May 31, 2020

Hey, is this for Craft CMS 3 only? I'm using version 2 and get an error of:

Template Error

Unknown "create" function. 
@juban

This comment has been minimized.

Copy link
Owner Author

juban commented May 31, 2020

Hi @JamesNock,

Yes, this is a Craft 3 tip. Unfortunately, the create method won’t be available in Craft 2.

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.