I have a one-pager layout with sections.
If i had a classic file structure with pages and subpages and wanted to add the class “active” to the currently active menu item i would be able to use
$child->isOpen()
, like here:
<?php foreach($children as $child): ?>
<li class="menu-item"><a<?php e($child->isOpen(), ' class="active"') ?> href="<?php echo $child->url() ?>"><?php echo $child->title()->html() ?></a></li>
<?php endforeach ?>
But as i need to construct a custom URL with an anchor for my section, i use the following:
<?php foreach($children as $child): ?>
<li class="menu-item"><a href="<?= $item->url() . '#' . str::slug($child->title()) ; ?>"><?= $child->title()->html() ?></a></li>
<?php endforeach ?>
Unfortunately i can’t use $child->isOpen()
for this.
How can i add the active class to my menu item?
My navigation in context:
<nav class="docs-nav" role="navigation">
<div class="accordion-container">
<?php
// nested menu
$items = $pages->visible();
// only show the menu if items are available
if($items->count()):
?>
<?php foreach($items as $item): ?>
<div class="accordion">
<input type="checkbox" id="docs-accordion-<?php echo $item->num() ?>" name="docs-accordion-checkbox" hidden <?php e($item->isOpen(), ' active') ?>>
<label class="accordion-header c-hand" for="docs-accordion-<?php echo $item->num() ?>"><?php echo $item->title()->html() ?></a></label>
<?php
// get all children for the current menu item
$children = $item->children()->visible();
// display the submenu if children are available
if($children->count() > 0):
?>
<div class="accordion-body">
<ul class="menu menu-nav">
<?php foreach($children as $child): ?>
<li class="menu-item"><a href="<?= $item->url() . '#' . str::slug($child->title()) ; ?>"><?php $child->title()->html() ?></a></li>
<?php endforeach ?>
</ul>
</div>
<?php endif ?>
</div>
<?php endforeach ?>
</div>
</nav>