Forum

How to Make Twitter...
 
Notifications
Clear all

How to Make Twitter Bootstrap Navbar Link Active in PHP?

 
(@administrator)
Member Admin

To make a Twitter Bootstrap navbar link active in PHP, you can use the active class provided by Bootstrap. Here's an example of how to do it:

 

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">My Website</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav">
      <li class="nav-item <?php if ($active == 'home') {echo 'active';} ?>">
        <a class="nav-link" href="index.php">Home</a>
      </li>
      <li class="nav-item <?php if ($active == 'about') {echo 'active';} ?>">
        <a class="nav-link" href="about.php">About</a>
      </li>
      <li class="nav-item <?php if ($active == 'contact') {echo 'active';} ?>">
        <a class="nav-link" href="contact.php">Contact</a>
      </li>
    </ul>
  </div>
</nav>

 

In this example, we are adding the active class to the nav-item the element that corresponds to the current page. To do this, we can set a variable called $active at the beginning of each page and then use it to determine which link should be active.

For example, on the index.php page, we can set $active it to 'home':

 

<?php
$active = 'home';
?>

 

On the about.php page, we can set $active to 'about':

 

<?php
$active = 'about';
?>

 

 

And so on.

By using this approach, the navbar link that corresponds to the current page will be highlighted as active.

 

 

 

Quote
Topic starter Posted : 13/02/2023 7:46 am
Share:
×