Collections
Pagination
You can create a Blade template that displays your collection items in a paginated format by including a pagination
key in the template's YAML front matter. The pagination header should include the collection
name and the perPage
count:
posts.blade.php
1---2pagination:3 collection: posts4 perPage: 55---6@extends('_layouts.master')7...
If you don't provide a
perPage
value in your template, a default value can be set for specific collection by adding aperPage
key to the collection's settings inconfig.php
, or globally by adding aperPage
key to the top level ofconfig.php
. Otherwise, the default value will be 10.
Once the pagination
has been defined in the header, the template will have access to a special $pagination
variable, which has several attributes:
$pagination->items
contains an array of collection items for the current page$pagination->currentPage
contains the page number of the current page$pagination->totalPages
contains the total number of pages$pagination->pages
contains an array of paths to each page
Note that the
pages
are indexed by their page number, i.e. they are 1-based. So you can refer to the paths of a page by the page number, i.e.$pagination->page[1]
will return the path to the first page.
$pagination->first
contains the path to the first page (the same as$pagination->path[1]
)$pagination->last
contains the path to the last page$pagination->next
contains the path to the next page$pagination->previous
contains the path to the previous page
Using these $pagination
attributes, you can build a set of pagination buttons and links:
1@if ($previous = $pagination->previous) 2 <a href="{{ $page->baseUrl }}{{ $pagination->first }}"><<</a> 3 <a href="{{ $page->baseUrl }}{{ $previous }}"><</a> 4@else 5 << < 6@endif 7 8@foreach ($pagination->pages as $pageNumber => $path) 9 <a href="{{ $page->baseUrl }}{{ $path }}"10 class="{{ $pagination->currentPage == $pageNumber ? 'selected' : '' }}">11 {{ $pageNumber }}12 </a>13@endforeach14 15@if ($next = $pagination->next)16 <a href="{{ $page->baseUrl }}{{ $next }}">></a>17 <a href="{{ $page->baseUrl }}{{ $pagination->last }}">>></a>18@else19 > >>20@endif
To display the items on each page, iterate over the $pagination->items
collection:
1@foreach ($pagination->items as $post)2 <h3><a href="{{ $post->getUrl() }}">{{ $post->title }}</a></h3>3 <p class="text-sm">by {{ $post->author }} • {{ date('F j, Y', $post->date) }}</p>4 <div>{!! $post->getContent() !!}</div>5@endforeach