adding ‘first’ and ‘last’ class to Joomla Menu items : Menu overrides

Share!

one often needs to define the first and last element in navigation menu. It is needed when you want to remove the last/first unwanted border or maybe if you want to highlight the first item differently. The effect can be achieved by adding an extra class “first” and “last” to the respective child elements of the menus. It is a much sought after feature and I feel should be made the default feature of joomla menu system.

Joomla has a mod_mainmenu module for creating menus. Joomla allows the users to create overrides to get this special enhancements. We would make an override to joomla’s ‘mod_mainmenu’ module to get out classification finctionality.

 

The overrides are placed in a folder named “html” inside your template folder. Inside ‘html’ place another folder called ‘mod_mainmenu’ to specify the override. Next, copy the file default.php from modules/mod_mainmenu/tmpl from your joomla filesystem to our folder(mod_mainmenu). I recommend you get your own file it may avoid any version related issues. Your default.php file is now located similar to:

templates/MYTEMPLATE/html/mod_mainmenu/default.php

open the file and navigate to the ‘ul’ component which looks like

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

We will add a few lines of code to this to get the ‘first’ and ‘last’ class in the menu items. Our new block will look like :

if ($node->name() == 'ul') {
	foreach ($node->children() as $child)
	{
		if ($child->attributes('access') > $user->get('aid', 0)) {
			$node->removeChild($child);
		}
	}
        //NEW CODE STARTS HERE
	$children_count = count($node->children());
	$children_index = 0;
	foreach ($node->children() as $child) {
		if ($children_index == 0) {
			$child->addAttribute('class', 'first');
		}
		if ($children_index == $children_count - 1) {
			$child->addAttribute('class', 'last');
		}
		$children_index++;
	}
        //ENDS HERE
}

We are done. Just update the file on your webserver and test it. Now the menu child items must get classified. You can now use these classes to transform the look of its children elements.

 

for joomla 1.6, 1.7

if ($item->deeper) {
      $class .= 'deeper ';
   }

Replace this with:

$currentitemcount ++;
   if ($item->shallower or $currentitemcount == count($list)) {
      $class .= 'last ';
   }
   
   if ($lastdeeper or $currentitemcount == 1) {
      $class .= 'first ';
   }
   
   
   if ($item->deeper) {
      $class .= 'deeper ';
      $lastdeeper = true;
   } else {
      $lastdeeper = false;   
   }
Share!

Leave a comment