Another CakePHP3 quick tip today, this time I'll explain how you can tweak the structure for the pagination helper. This is especially helpful for people using front-end frameworks such as Bootstrap that require a certain markup structure for pagination.

This is a surprisingly easy thing to do in the new version of the framework, now let's get to it.

Let's start by setting up our pagination within a controller, in my case PostsController.

We need to first define a paginate array with our options such as limit and order, we also need to load the Paginator component.

Open your PostsController and set these up like below:

class PostsController extends AppController
{
    public $paginate = [
        'limit' => 10
    ];

    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('Paginator');
    }
}

So as you can see above, we've setup our pagination options and we've called in the Paginator component.

Now we need to load in our Paginator helper, this is where we define our template. Just above your $paginate array, load in your helper.

public $helpers = [
    'Paginator' => ['templates' => 'paginator-templates']
];

Ok cool! Now we've done that we just need to define our template, do this by creating the file paginator-templates.php inside your config directory.

To take a look at the multiple template options, head over to the CakePHP Paginator page : http://book.cakephp.org/3.0/en/views/helpers/paginator.html#template-names

Create your config array inside the file you've just created and for demonstration purposes I'll show you how to handle the numbers and next / previous links.

$config = [
    'number' => '<li><a href="{{url}}">{{text}}</a></li>',
    'current' => '<li class="active"><a href="#">{{text}}</a></li>',
    'nextActive' => '<li><a aria-label="Next" href="{{url}}">{{text}}</a></li>',
    'nextDisabled' => '<li class="next disabled"><a aria-label="Next"><span aria-hidden="true">»</span></a></li>',
    'prevActive' => '<li><a aria-label="Previous" href="{{url}}">{{text}}</a></li>',
    'prevDisabled' => '<li class="prev disabled"><a aria-label="Previous"><span aria-hidden="true">«</span></a></li>'
];

Now to elaborate on the options above, most however are self explanatory.

  1. Number = the numbers between your next and previous tags 1 2 3
  2. Current = this is the active state HTML for the number tags

next, nextActive, prev & prevActive are all self explanatory - they handle the next and previous links that sit at the side of the numbers on most pagination structures.

And that covers it, if there's anything you're confused about I refer you back to the CakePHP 3 book - the pagination setup is fully documented.

http://book.cakephp.org/3.0/en/views/helpers/paginator.html#template-names

Thanks for reading, any questions as usual drop them in the comments!