Default fallback in route

I have a route set up to direct certain menu items to the homepage (there, I use the slug to do some filtering of the main content)

Here’s my route:

  array(
    'pattern' => '(:any)',
    'action' => function($slug) {
      $page = (kirby()->site()->pages()->find($slug)->intendedTemplate() == 'category') ? ('/home') : ('/' . $slug);
      return $page;
    }
  )

It works as expected, and I get to the correct pages. /videos is a category, and I get the homepage, /contact is not, and I get the contact page.

But, I noticed that this is messing with the $page->isActive() function. When I’m at /contact, $page->isActive() returns false. I’m assuming this is because of the way I’m returning the page: '/' . $slug

How do I allow a route to fall back to its default if certain requirements aren’t met?

This should work:

array(
    'pattern' => '(:any)',
    'action' => function($slug) {
      $page = (kirby()->site()->pages()->find($slug)->intendedTemplate() == 'category') ? page('home')  : page($slug);
      return $page;
    }
  )
2 Likes

This still doesn’t workwith ->isActive(). A workaround is easy enough, though, so it’s not a big deal, and I can’t think of any other scenarios where it might be a problem.

	<?php
	$infoPages = $pages->visible()->filterBy('intendedTemplate', 'page');
	foreach($infoPages as $infoPage): ?>

               // does not work (returns false)
                <?php $class = ($infoPage->isActive()) ? "active" : ""; ?>
               // works
		<?php $class = ($infoPage->slug() == $page->slug()) ? "active" : ""; ?>
		
                <h3 class="menu__item"><a href="<?= $infoPage->url() ?>" class="<?= $class ?>"><?= $infoPage->title() ?></a></h3>
	<?php endforeach ?>
1 Like

As regards setting a page active in a route, see this thread.