Search code examples
phpmenumenubar

Make a self-aware menubar


So, In the website I'm currently designing (HTML5, PHP, JS/JQuery and Bootstrap), I've got a basic menubar at the top of the page. Just your normal

    <ul>
    <li><a href="index.php">Home</a></li>
    <li class="active"><a href="about.php">About</a></li>
    <li><a href="players.php">Players</a></li>
    <li><a href="rules.php">Rules</a></li>
    </ul>

Now, there's a lot more to this, such as a login button, etc, but basically it's adding a LOT of clutter to the top of my pages, and I was wondering if there would be any way to put it in a header.php file.
My issue is how I can use it in multiple webpages and still have the class="active" part. The only thing I thought of was making a function where it takes the page name as a string and go through each line and does if (the page is the same as the link) { echo the element with the class="active" } else { echo the element without the class }
Thanks!


Solution

  • You probably want to extract your header to header.php as you said, and then use the PHP include method.

    <?php
    
    include 'header.php';
    
    ?>
    

    As far as selecting the 'active' class, you could pass and set an '$active' variable on each page. And then, since the included file inherits the scope from the page where it's included, you can get the variable and preform your logic in the header.php page.