Navigate into a collection with hasNext/hasPrev

Just as an update: I needed the same functionality for a project and it works fine; all that is needed is to copy the code into custom page methods:

page::$methods['getNext'] = function($page, Children $siblings, $sort = array(), $visibility = false) {
  if($sort) $siblings = call(array($siblings, 'sortBy'), $sort);
  $index = $siblings->indexOf($page);
  if($index === false) return null;
  if($visibility) {
    $siblings = $siblings->offset($index+1);
    $siblings = $siblings->{$visibility}();
    return $siblings->first();
  } else {
    return $siblings->nth($index + 1);
  }
};

page::$methods['getPrev'] = function($page, Children $siblings, $sort = array(), $visibility = false) {
  if($sort) $siblings = call(array($siblings, 'sortBy'), $sort);
  $index = $siblings->indexOf($page);
  if($index === false or $index === 0) return null;
  if($visibility) {
    $siblings = $siblings->limit($index);
    $siblings = $siblings->{$visibility}();
    return $siblings->last();
  } else {
    return $siblings->nth($index - 1);
  }
};

Then you can use those methods in your next/prev snippet:

<nav>
  <ul class="prevNext">
    <?php if($prev = $page->getPrev($collection)): ?>
      <li class="previous"><a href="<?= $prev->url() ?>">prev</a></li>
    <?php endif ?>
    <?php if($next = $page->getNext($collection)): ?>
      <li class="next"><a href="<?=$next->url()?>">next</a></li>
    <?php endif ?>
  </ul>
</nav>

You only have to add a way to preserve the original collection, by passing a parameter or storing the values in a session or whatever.

1 Like