Menu highlighting with CakePHP 1.2

As far as I can tell CakePHP 1.2 does not have a good navigation menu helper at the moment. That is probably because they have a good link builder that is very flexible so you can just throw some css togeather and make ome very decent looking menus. You can make them look good but wouldn’t it be nice to have a highlight effect that shows the current menu option you selected.

I found a pretty decent solution. It will figure out which section of the website you are in and highlight the proper link. It is pretty crude but it works for what I want it to do.

class MenuHelper extends Helper {
	var $helpers = array('Html');
 
/**
 * Highlight a menu option based on path
 *
 * A menu path gets passed and it compares to requestd path and sets the call to be highlighted.
 * Use regular ereg expressions in the pattern matching.
 *
 * @param path for wich the nav item should be highlighted
 * @param optional normal class to be returned, default navLink
 * @param optional highlight class to be returnd, default navLinkSelected
 * @return returns the proper class based on the url
 */
	function highlight($path, $normal = 'navLink', $selected = 'navLinkSelected') {
		$class = $normal;
		$currentPath = substr($this->Html->here, strlen($this->Html->base));
		// if there is a star in the path we need to do different checking
		$regs = array();
		if (ereg($path,$currentPath,$regs)){
			$class .= " ".$selected;
		}
		return $class;
    }
}

A usage example would be something like the following…
Create something like this for each menu item. The string in highlight should be the path part you want the menu item highlighted for.

<?php echo link('Home','/', array('title' => 'Home', 'class' => $menu->highlight("/$"))) ?>
<?php echo link('My Account','/users', array('title' => 'My Account', 'class' => $menu->highlight('/users*'))) ?>

You also need to add some CSS for the menus. This is just an example. This code is used at RewardChamp if you want to take a look.

#navMenu {
	width:750px;
	margin:0px auto;
	height:35px;
}
 
#navMenu a.navLink {
	height:13px;
	font:normal 12px Helvetica;
	color:#FFF;
	float:left;
	padding:11px 12px;
	margin:0px;
}
 
#navMenu a.navLink:hover {
	background:#3F3F3F;
	color:#FFF;
	text-decoration: none;
}
 
#navMenu a.navLinkSelected {
	background: #B61D1D;
}
 
#navMenu a.navLinkSelected:hover {
	background: #B61D1D;
}