Skip to content

Instantly share code, notes, and snippets.

@juban
Last active April 3, 2024 09:26
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juban/a55781d49f2f68ec3ca47979bcaaa49a to your computer and use it in GitHub Desktop.
Save juban/a55781d49f2f68ec3ca47979bcaaa49a to your computer and use it in GitHub Desktop.
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
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
Copy link
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.

@mightyfineyall
Copy link

This is fantastic - thanks so much for this.

@petenice
Copy link

Thank you!

@AmarHuda1
Copy link

hi @juban can you provide me the documentation for this create() function? i can't found it in craft cms documentation

@AmarHuda1
Copy link

thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment