Pagination - simple & small twig version - based on page collections

You can use this twig code on any template where you would like to add a listing with pagination.
To configure your page collection for your needs look at the Grav documentation regarding collections.

This is where you define your collection

{% set collection = page.collection({
    'items': '@self.children', 
    'pagination': true, 
    'order': {'by': 'title'}, 
    'limit': 2}) 
%}

These are the needed variables/calculations that the pagination needs.
Usually you won’t need to change these

{% set itemsInCollection = page.collection({'items': collection.params.items})|length %}
{% set itemsPerPage = collection.params.limit %}
{% set pagesInCollection = (itemsInCollection / itemsPerPage)|round(0, 'ceil') %}
{% set currentPage = uri.param('page')|default('1') %}

This is where the pagination gets displayed. Change with caution

   <ul class="pagination">
	{% for i in range(1, pagesInCollection) %}
		<li {% if currentPage is same as('' ~ i ~ '') %} class="currentpage" {% endif %}>
			<a href="{{ page.url ~ '/page' ~ system.param_sep ~ i }}">{{ i }}</a>
		</li>
	{% endfor %}
	</ul>

Another version: Listing of pages that use a template.

`

Amount of listing items - pagination by template


When using dynamic twig variables, turn off the page cache !

	<!-- setup variables -->
	{% set headerCollection = page.collection({ 'items': '@root.children' }) %}
	{% set typesInCollection = headerCollection.ofOneOfTheseTypes(['image-demo','divider-demo','fields-demo']) %}
	{% set itemsPerPage = 2 %}

	<!-- page amount calculations -->
	{% set itemsInCollection = typesInCollection|length %}
	{% set pagesInCollection = (itemsInCollection / itemsPerPage)|round(0, 'ceil') %}
	
	<!-- listing item amount calculations -->
	{% set currentPage = uri.param('page')|default('1') %}
	{% set sliceOffset = (currentPage * itemsPerPage) - itemsPerPage %}

	<!-- fallback - if itemsPerPage is set to 1 -->
	{% if not itemsPerPage is same as(1) %}
		{% set sliceLength =  sliceOffset + itemsPerPage %}
	{% else %}
		{% if sliceOffset ==  0 %}
			{% set sliceLength =  1 %}
		{% else %}
			{% set sliceLength =  sliceOffset %}
		{% endif %}
	{% endif %}

	<!-- the rendering -->
	{% set theCollection = typesInCollection.slice(sliceOffset,sliceLength) %}

	
	<!-- the pagination -->
	<ul class="pagination">
	{% for number in range(1, pagesInCollection) %}
		<li {% if currentPage is same as('' ~ number ~ '') %} class="currentpage" {% endif %}>
			<a href="{{ page.url ~ '/page' ~ system.param_sep ~ number }}">{{ number }}</a>
		</li>
	{% endfor %}
	</ul>

	<!-- the list items -->
	{% for child in theCollection %} 
	   {{ child.title }} <br>
	{% endfor %}`
1 Like