I have a header which displays page links via <li>
and <a>
tags.
Here is a portion of the header:
<div class="collapse navbar-collapse" id="main-navbar">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="/">
Home
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="items">
Explore
</a>
</li>
</ul>
</div>
How can I set the class of the <li>
that belongs to the active link to active?
I have code elsewhere in my project that sets an active link, but it is setting it from an array and I can't figure out how to apply it here.
Here is the code that is working from another page:
<?php
foreach ($categories as $category_side){
$cat_class = '';
if (isset($active_category) && ($active_category==$category_side['Category']['id'])){
$cat_class = 'active';
}
?>
<li>
<a href="/categories/view/<?php echo $category_side['Category']['id']; ?>" class="category-item <?php echo $cat_class; ?>">
<?php echo $category_side['Category']['name_'.$txt_lang]; ?>
</a>
</li>
<?php } ?>
I found this how to add active class in current page in CakePhp but I can't figure out how to apply it to the first block of code above.
How can I convert the first block of code above, using PHP or CakePHP functions so that the active menu's <li>
class is set to "active".
Solution
Following Sehdev's answer below (accepted answer), I was able to create a solution for assigning the active class, to the active hyperlink in the header menu.
The controller and action in combination were not enough, as some pages linked to the same controller and action, but were actually different rendered views.
The solution was to use $this->here to extract the current url, like so:
(tested in CakePHP 2.9.1)
<?php
$activeurl = $this->here;
?>
<ul class="navbar-nav mr-auto">
<li class="nav-item <?php echo (!empty($activeurl) && ($activeurl == '/'))?'active' :'inactive' ?>">
<a class="nav-link" href="/">
Home
</a>
</li>
<li class="nav-item <?php echo (!empty($activeurl) && ($activeurl == '/items'))?'active' :'inactive' ?>">
<a class="nav-link" href="/items">
Explore
</a>
</li>
</ul>