Active Tab Navbar In PHP
posted on 2014-09-21 by Spencer Bravo
This post is about how I set up my navbars for websites. It enables the navbar to be highlighted based on the page you're on and doesn't require you to put a different <nav> section on every page. This setup also gives the ability to create the header on a completely different file (header.inc.php), while still making the navbar active based on the page.
Now to the code:
<?php
$category_explode = explode("/",$_SERVER['REQUEST_URI']);
$site = $category_explode[0];
$page = $category_explode[1];
$post = $category_explode[2];
$nnav = " ";
$nav = '<ul class="nav navbar-nav">
<li class="inactive"><a href="/">Home</a></li>
<li class="inactive"><a href="/bash/">Bash</a></li>
<li class="inactive"><a href="/viml/">VimL</a></li>
<li class="inactive"><a href="/web/">Web</a></li>
<li class="inactive"><a href="/about/">About</a></li>
</ul>';
switch ($page) {
case "":
$nnav = str_replace("<li class=\"inactive\"><a href=\"/\">Home</a></li>","<li class=\"active\"><a href=\"/\">Home</a></li>",$nav);
break;
case "bash":
$nnav = str_replace("<li class=\"inactive\"><a href=\"/bash/\">Bash</a></li>","<li class=\"active\"><a href=\"/bash/\">Bash</a></li>",$nav);
break;
case "viml":
$nnav = str_replace("<li class=\"inactive\"><a href=\"/viml/\">VimL</a></li>","<li class=\"active\"><a href=\"/viml/\">VimL</a></li>",$nav);
break;
case "web":
$nnav = str_replace("<li class=\"inactive\"><a href=\"/web/\">Web</a></li>","<li class=\"active\"><a href=\"/web/\">Web</a></li>",$nav);
break;
case "about":
$nnav = str_replace("<li class=\"inactive\"><a href=\"/about/\">About</a></li>","<li class=\"active\"><a href=\"/about/\">About</a></li>",$nav);
break;
default:
$nnav = $nav;
break;
}
?>
You can view the most current version of this code at https://github.com/spravo13/active-tab-navbar-codeshrub
All I did was create a variable ($nav) to store the basic navigation and then based on what page the user is on I used a switch statement to edit $nav and store the changes in the variable $nnav.
Then all you have to do is include the variable "$nnav" where you want your navigation. Heres an example of using it(this example is later on in the same file, if you don't include your navigation in a seperate file, just include the file with this code in the file you want.
<div class="nav">
<?php
echo $nnav;
?>
</div>
I hope this post is useful! If you have any questions or comments please don't hesitate to email us at CSTeam@CodeShrub.com
posted in web