Previous next navigation

Some time ago, I used the following code to switch between page children:

      <ul>
        <?php if ($page->hasPrevListed()): ?>
          <li><a href="<?= $page->prevListed()->url() ?>">&larr;</a></li>
        <?php else: ?>
          <li><span>&larr;</span></li>
        <?php endif ?>
        <?php if ($page->hasNextListed()): ?>
          <li><a href="<?= $page->nextListed()->url() ?>">&rarr;</a></li>
        <?php else: ?>
          <li><span>&rarr;</span></li>
        <?php endif ?>
      </ul>

Now, I want switch site children of a specific template but the filtering does not work.

  <?php if ($site->children()->filterBy('template', 'work')->listed()->count() > 1): ?>
    <ul>
      <li><a href="<?= $page->prevListed()->filterBy('template', 'work')->url() ?>">&larr;</a></li>
      <li><a href="<?= $page->hasNextListed()->filterBy('template', 'work')->url() ?>">&rarr;</a></li>
    </ul>
  <?php endif ?>

May I use this function: $page->hasTemplate(): bool? Or do I have to work with variables? I would like to loop thourgh the pages. Last page to first page and vice versa.

The problem here is that $page->prevListed() returns a page object which cannot be filtered, you can only filter collections. What you can do is pass a collection to hasPrevListed() etc., see docs: $page->hasPrevListed() | Kirby CMS

See also: hasPrevListed() only for pages with toggle field is true

1 Like

Thank you very much. It works well!

      <?php
      $works = site()->index()->filterBy('template', 'work')->listed();
      ?>

      <?php if ($works->count() > 1): ?>
        <ul>
          <?php if ($page->hasPrevListed($works)): ?>
            <li><a href="<?= $page->prevListed($works)->url() ?>">&larr;</a></li>
          <?php else: ?>
            <li><a href="<?= $works->last()->url() ?>">&larr;</a></li>
          <?php endif ?>

          <?php if ($page->hasNextListed($works)): ?>
            <li><a href="<?= $page->nextListed($works)->url() ?>">&rarr;</a></li>
          <?php else: ?>
            <li><a href="<?= $works->first()->url() ?>">&rarr;</a></li>
          <?php endif ?>
        </ul>
      <?php endif ?>