Getting the URL of the next page


#1

Hello,

What’s the most appropiate way to get a link to the previous or following page in a site from a block? I would be expecting to get the same URL as in the existing Prev | Next links at the bottom.

Thank you!


#2

You can probably reuse the Prev | Next system:

//In your controller
$page = $this->api()->read('site_pages', [
    'slug' => $this->params('page-slug'),
    'site' => $site->id(),
])->getContent();
$linkedPages = $page->site()->linkedPages();
while ($linkedPage = current($linkedPages)) {
    if ($page->id() === $linkedPage->id()) {
        $nextPage = next($linkedPages);
        break;
    }
    $prevPage = $linkedPage;
    next($linkedPages);
}

#3

Thank you for your help. I didn’t know how to access the controller from the block render function. Finally got it from $block and used the code you suggested from SitePagePagination:

public function render(PhpRenderer $view, SitePageBlockRepresentation $block)
    {
        // ...
        // Get next and prev urls
        $page = $block->page();
        $linkedPages = $page->site()->linkedPages();
        while ($linkedPage = current($linkedPages)) {
            if ($page->id() === $linkedPage->id()) {
                $nextPage = next($linkedPages);
                break;
            }
            $prevPage = $linkedPage;
            next($linkedPages);
        }     
        
        if($nextPage!=null)
            $nextUrl = $nextPage->url();
        else
            $nextPage = '';

        if($prevPage!=null)
            $prevUrl = $prevPage->url();
        else
            $prevUrl = '';
        // ...