Adding 'active' class to multi-level menu with kirby navigation plug-in

Hello, I am having trouble getting an ‘active’ class added to the current page in a navigation menu using the kirby navigation plug-in, using the code below I get an ‘active’ class added to every menu item, any idea’s on how to solve this would be greatly appreciated.

<nav>
	<ul class="nav-list">
		<?php foreach($site->mainnavigation()->toStructure() as $navigation): ?>
		<li <?php e($navigation->isOpen(), 'class="active"') ?>><a aria-label="<?php echo $navigation->text() ?>"
				href="<?php echo $navigation->url(); ?>"><?php echo $navigation->text() ?></a>
			<?php if($navigation->children()->isNotEmpty()): ?>
			<ul class="menu vertical nested">
				<?php foreach($navigation->children()->toStructure() as $children): ?>
				<li <?php e($children->isOpen(), 'class="active"') ?>><a aria-label="<?php echo $children->text() ?>"
						href="<?php echo $children->url() ?>"><?php echo $children->text() ?></a>
					<?php if($children->children()->isNotEmpty()): ?>
					<ul class="menu vertical nested">
						<?php foreach($children->children()->toStructure() as $subchildren): ?>
						<li <?php e($subchildren->isOpen(), 'class="active"') ?>><a aria-label="<?php echo $subchildren->text() ?>"
								href="<?php echo $subchildren->url() ?>"><?php echo $subchildren->text() ?></a></li>
						<?php endforeach ?>
					</ul>
					<?php endif ?>
				</li>
				<?php endforeach ?>
			</ul>
			<?php endif ?>
		</li>
		<?php endforeach ?>
	</ul>
</nav>

Hi. I’m not too familiar with the kirby-navigation plugin (looks like you are referring to chrisbeluga/kirby-navigation), but from a quick glance it seems that the mainnavigation field is an array, i.e. your variable $navigation is not a page object (which would be a requirement for the isOpen method to be available).

You could try something like e($navigation->url() == $page->url(), 'class="active"') to instead compare the URL of the menu item at hand and the currently displayed page.

1 Like

Thank you, I will give that a try.

Hi @FatBuddha sorry for the late reply, the answer by @sebastiangreger should work though.

I’m planning on updating the plugin to include this option in the near future but haven’t put any timescales on this as other things keep getting in the way.

I’ll update this thread as and when it’s done incase any one else runs into this issue in future