I have a site menu that is build with a structure because the client wants to be able to manage it themself and it can contain pages from the site, external links and pdf documents. Unfortunately because of this I can’t use $page->isActive()
to get the active page an active class.
Not only the parent pages itself should get the active class but also the parent pages if you’re on a child page. I solved this by using this php:
$protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === 0 ? 'https://' : 'http://';
$actual_link = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$parent_link = dirname("$actual_link");
And I add an active class to pages like this:
<?php foreach ($site->pagesInMenu()->toStructure() as $menuItem): ?>
<li <?php e($actual_link === $menuItem->menuItemURL()->toLinkObject()->url() || $parent_link === $menuItem->menuItemURL()->toLinkObject()->url() , ' class="active"') ?>> <a <?php if ($menuItem->newTab()->toBool() === true): ?> target='_blank' <?php endif ?> href="<?= $menuItem->menuItemURL()->toLinkObject()->url() ?>"><h3><?= $menuItem->menuItemText() ?></h3></a></li>
<?php endforeach ?>
Which works fine for all the pages and children of the pages but there is also a home menu item that always get’s the active class. Is there a way to exclude this within this solution? Or is there a better solution for this within Kirby?