Simple PHP Menus

Simple PHP Menus

October 17, 2013 Web Design 0

During my Android programming course at BCIT I recently learned about the DRY (Don’t Repeat Yourself) principle. Oddly enough, this principle was coined by another Dave Thomas! The concept behind the DRY principal is that you should never repeat code.

In coding websites, many times the menu bar or navigation is copied between the HTML files and the styling of the link for the current page may be changed to make it stand out. In order to make things DRY I’ve been coding my sites in PHP when possible lately and using includes to add the navigation to various pages. This is fairly straightforward, but the tricky part is styling the links for the current page, like the link in the following image.

Menu bar with the Portfolio link highlighted

Here is a simple solution I found:

First, near the top of every page add a line of PHP with something like this:

<?php $thisPage="Blog"; ?>

In the above example $thisPage is a variable. Simply type the name of the page in place of Blog.

Now, create your navigation as its own file. I called it nav.php and it looks something like this:

<div class="nav">
  <ul class="nav navbar-nav">
    <li
      <?php if ($thisPage=="Home") 
      echo " class=\"active\""; ?>>
      <a href="index.php">Home</a>
    </li>
    <li
      <?php if ($thisPage=="About") 
      echo " class=\"active\""; ?>>
      <a href="#about">About</a>
    </li>
    <li 
      <?php if ($thisPage=="Portfolio") 
      echo " class=\"active\""; ?>>
      <a href="http://bootstrap.dthomas.ca/portfolio.php">Portfolio</a>
    </li>
    <li
      <?php if ($thisPage=="Blog") 
      echo " class=\"active\""; ?>>
      <a href="blog.php">Blog</a>
    </li>
    <li
      <?php if ($thisPage=="Contact") 
      echo " class=\"active\""; ?>>
      <a href="contact.php">Contact</a>
    </li>
  </ul>
</div>

In the above example each “if” statement checks to see if the current page’s $thisPage variable (which you declared in the first step) is the same . If it is then it assigns it a class of “active”, making the link for the current page stand out like in the image above.

Finally, you add the navigation to every page by simply adding the following line of PHP in the proper spot in your HTML code:

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

And that’s it! I hope you found this useful. If you have any questions or suggestions for improving this post, please let me know in the comments below.

Leave a Reply