Create Dynamic Navigation Menus


Use PHP to build a navigation menu widget that works consistently across your site.

Writing the navigation menu for your site can be a pain. You don't want to write the same code over and over on every page. Ideally, you would have a PHP menu function that would render the menu with the current page highlighted. This hack gives you that simple menu function (for the low cost of this book, no less!).

The Code

Save the code in Example 1, which demonstrates the use of menu.php as index.php.

Example 1. Using the menu library
<?php
require_once( "menu.php" );
 
$page = "home";
if ( $_GET['page'] )
               $page = $_GET['page'];
?>
<html>
<head>
<title>Page - <?php echo($page); ?></title>
<?php echo menu_css( ); ?>
</head>
<body>
<table cellspaceing="0" cellpadding="5">
<tr>
<td width="200" valign="top">
<?php page_menu( $page ); ?>
</td>
<td width="600" valign="top">
Page: <?php echo( $page ); ?>
 
</td>
</tr>
</table>
</body>
</html>

Example 2 shows the library, which is surprisingly simple.

Example 2. Making everything work with the PHP library, menu.php
<?php
function menu_css( ) {
?>
<style type="text/css">
.menu-inactive, .menu-active {
               padding: 2px;
               padding-left: 20px;
               font-family: arial, verdana;
}
.menu-inactive { background: #ddd; }
.menu-active { background: #000; font-weight: bold; }
.menu-inactive a { text-decoration: none; }
.menu-active a { color: white; text-decoration: none; }
</style>
<?php
}
 
function menu_item( $id, $title, $current ) {
$class = "menu-inactive";
if ( $current == $id )
               $class = "menu-active";
?>
<tr><td class="<?php echo($class); ?>">
<a href="index.php?page=<?php echo( $id ); ?>">
<?php echo( $title ); ?>
</a>
</td></tr>
<?php
}
 
function page_menu( $page ) {
?>
<table width="100%">
<?php menu_item( 'home', 'Home', $page ); ?>
<?php menu_item( 'faq', 'FAQ', $page ); ?>
<?php menu_item( 'download', 'Download', $page ); ?>
<?php menu_item( 'links', 'Links', $page ); ?>
<?php menu_item( 'credits', 'Credits', $page ); ?>
</table>
<?php
}
?>

index.php creates the menu by calling the page_menu function and specifying the page ID. The ID of the page is used to decide which menu item is selected. The index.php script also calls the menu_css function to set up the CSS styles for the menu.

You can change the makeup of the menu by altering the bottom portion of the menu.php file to add or remove menu items. You can also change the look and feel of the menu by altering the CSS class definitions in the menu_css function.

Running

Upload the code to the server and point your browser at index.php. Your display should look like Figure 1.

Figure 1. The home page

Now click on the FAQ link; you should see something like Figure 2.

Figure 2. The FAQ page


0 komentar:

top