Adding a unique class to the last item in a menu

11.07.2008

As I start to harness the true power of the Joomla 1.5 framework and template over-rides I'm finding that you can really do anything imaginable. As I was working on the new site for Zuno Studios I wanted to add special CSS styling to the last menu item in my menus.

This was really easy. All it takes are some changes to the mod_mainmenu module. Mod_mainmenu is the core Joomla! module that controls the output of your menus.  I created a template over-ride for the mod_mainmenu module in order to keep the J! core untouched. This is key to easily updating your J! core.

To create a template override simply create a directory in your default template folder called "html". Within that directory create a new folder for each item you want to over-ride (modules and components). In this case I am wanting to over-ride the mod_mainmenu module so my default template directory looks like this...

siteroot/templates/default_template/html/mod_mainmenu

Next copy the files in the siteroot/modules/mod_mainmenu/tmpl directory to the over-ride directory we just created in the default template folder. This will give you the neccessary files to alter for the new html output.

Now whatever we change in this file will over-ride the default view for the mod_mainmenu module.

With this file open, siteroot/templates/default_template/html/mod_mainmenu/default.php, make the change below, which is located at approximately line 27.

Original code

if ($node->name() == 'ul') {
foreach ($node->children() as $child)
{
if ($child->attributes('access') > $user->get('aid', 0)) {
$node->removeChild($child);
}
}
}

New code

if ($node->name() == 'ul') {
$i = 0;    
foreach ($node->children() as $child)
{
if ($child->attributes('access') > $user->get('aid', 0))
{
$node->removeChild($child);
}
if($i == count($node->children())-1)
{
$child->addAttribute('class', $node->attributes('class').' last');
}
$i++;
}
}

As you can see I added a class called "last" to the last menu item. I created a variable, $i and set it to 0 (zero) and incremented once for each child in the foreach loop. Then I called an if statement and checked if we were on the last child or not. If yes, then add the "last" class to it.

Template overrides like this give you all the power you need to create great CSS based sites. They also make your Joomla! site very flexible in terms of swapping out templates and keeping the J! core true.