Last active
April 3, 2024 09:26
-
-
Save juban/a55781d49f2f68ec3ca47979bcaaa49a to your computer and use it in GitHub Desktop.
Paginate any array within Craft CMS 3 templates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% 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 %} |
Hi @JamesNock,
Yes, this is a Craft 3 tip. Unfortunately, the create method won’t be available in Craft 2.
This is fantastic - thanks so much for this.
Thank you!
hi @juban can you provide me the documentation for this create()
function? i can't found it in craft cms documentation
thank you
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, is this for Craft CMS 3 only? I'm using version 2 and get an error of: