tags:

views:

43

answers:

2

Is there a good tutorial on creating a selected navigation menu using PHP?

+2  A: 

This is a common problem that doesn't really have an elegant one-size-fits-all solution. It depends primarily on how you store your list.

Basic answer:

  1. Put nav list items in an array
  2. Iterate over array to output html "<li>$item</li>"
  3. Check each item to see whether it's the current page (more below)
    • If current item is the current page, add an html class to it (i.e. class="current")

The hard part is figuring out which page is the current page.

Three ways to approach this problem:

  1. (Most difficult) Strip part of the path request (http://blah/my-page) and compare it to some data in your nav list.
  2. (Most maintenance) Define a variable per-page that matches something in your nav list.
  3. (Most setup / overhead) Use a foreign key relationship between nav item and page in your database schema

I've done all three.

  • Option 1 works and is the most robust (you can apply it to multiple navigation lists or multiple tiers in a tree), but is hard to do correctly in a portable fashion, and I have some reservations about it.
  • Option 2 is the easiest to setup initially, but you have to keep track of data in several places when you add or remove pages. I dislike maintenance.
  • Option 3 is the easiest to maintain but requires a database (and requires extra planning if you want to create nav list entries that aren't stored in the database or don't have a matching page handled by the database). This is the best way to go for bigger projects.

If there's a better solution than those, I'd like to know because this problem always bugs me.

Example of #2

Option two is the easiest, so here's a simple implementation.

$nav = array(
    '/' => 'Home',
    '/portfolio/' => 'Portfolio',
    '/contact/' => 'Contact',
);

function nav($current)
{
    GLOBAL $nav;
    $output = '';
    foreach($nav as $key => $var)
    {
        # First bit of common HTML
        $output .= '<li><a';
        if ($current == $var)
        {
            # add "current" class only for the to-be highlighted one
            $output .=' class="current"';
        }
        # finish off common HTML
        $output .= ' href="'.$key.'">'.$var.'</a></li>'."\n";
    }
    return $output;
}

echo nav('Home');

Obviously you need to supply a CSS rule to change the formatting on li.current, but that's the easy part.

banzaimonkey
+1  A: 

check this link:

http://www.finalwebsites.com/tutorials/dynamic-navigation-list.php this may help you

Ankur Mukherjee