Full example of pagination using Nette\Utils\Paginator

Notice: This thread is very old.
MattheusPirovani
Member | 2
+
+1
-

Hello everyone,

in this post i will show you a full example of how to use the Nette\Utils\Paginator class.

Let's use the tutorial Blog example of the Nette documentation.

Change your renderDefault method, of the HomepagePresenter, to this:

public function renderDefault($page = 1, $itens = 0)
{

    $paginator = new Nette\Utils\Paginator;
    $paginator->setItemsPerPage(1); // the number of records on page
    $paginator->setPage($page); //current page, default 1

    $posts = $this->database->table('posts')
                                            ->order('created_at DESC')
                                            ->limit($paginator->getLength(), $paginator->getOffset());

    //if itens == 0 count how many posts in posts table
    if( $itens == 0 ){

        $this->totalPosts = $this->database->table('posts')->count();
    }  else {

        $this->totalPosts = $itens;
    }

    $paginator->setItemCount( $this->totalPosts );

    $this->template->totalPosts = $paginator->getPageCount();
    $this->template->posts = $posts;
    $this->template->page = $paginator->page;

}

Now, there are two news parameters, the first page defines the current page and the second one itens the total number of posts. The logic has changed slightly , but remained simple.

You need to change your default.latte, to add the loop for the links:

{for $i = 1; $i <= $totalPosts; $i++}

    {if $i == $page}

        <strong>{$i}</strong>

    {else}

        <a href="{link Homepage:default $i, $totalPosts}">{$i}</a>

    {/if}

{/for}

Above, the loop is printing the links and if the current item its equal of the current page just show the page number without link.

hope it helps you. :)

tpr
Member | 55
+
0
-

Thanks, good to have such tutorials around.

You have a typo: itens → items

And I would use Latte's foreach instead of the “for” loop (and $iterator->counter instead of $i), just to make it more Nette-ish :)

MattheusPirovani
Member | 2
+
0
-

tpr wrote:

Thanks, good to have such tutorials around.

You have a typo: itens → items

And I would use Latte's foreach instead of the “for” loop (and $iterator->counter instead of $i), just to make it more Nette-ish :)

Itens was a mistake, because in portuguese (i'm from Brazil) itens its plural of item :)

Yes, foreach its a elegant way, but for its universal :)

Last edited by MattheusPirovani (2015-06-08 00:11)

tpr
Member | 55
+
0
-

for: Sim, estou ciente de que, graças :)