user3531149
user3531149

Reputation: 1539

How to display pagination on twig template

This is how the pagination on the controller works

 /**
     *@Route("/rating/{page}",name="testing")
     */
    public function pagesAction($page,Request $request)
    {
        // retrieve GET variables
        $pageNumber = $request->query->get('pageNumber');
        $pageSize = $request->query->get('pageSize');

                $em = $this->getDoctrine()->getManager();
                $qb = $em->createQueryBuilder();

                $results = $qb->add('select', 'p')
                    ->add('from', 'GabrielUploadBundle:Post p')
                    ->add('where', 'p.upvotes > 100')
                    ->add('orderBy', 'p.createdAt ASC')
                    ->setMaxResults($pageSize)
                    ->setFirstResult($pageSize * ($pageNumber - 1))
                    ->getQuery();


                return $this->render('GabrielLayoutBundle:Worldpage:content_loop.html.twig',array('posts'=>$results->getResult())); 
    }

now I only have to pass the pageNumber and pageSize for the URL (it works so far)

/rating/front?pageNumber=1&pageSize=3

All I need to know is how to display the results like this pagination

I've been struggling with this step since I don't know how to calculate the number of results and how to get the "next " and previous buttons to work

Upvotes: 1

Views: 4449

Answers (1)

Nicolai Fröhlich
Nicolai Fröhlich

Reputation: 52473

Please take a look at KnpLabs/KnpPaginatorBundle.

It's one of the TOP 10% most used bundles out there.

The bundle provides overrideable default templates for rendering the pagination buttons and is very easy to integrate into your project.

If you don't want to use the bundle ... it's source code is definitely a good place to look for inspiration.


Your current implementation lacks a second upfront query to get the total number of posts.

Without knowing the total number of posts ... you won't be able to determine the number of buttons to show.

Upvotes: 3

Related Questions