| Joomla! output override of mod_mainmenu |
| Monday, 19 January 2009 10:04 |
|
Joomla! has introduced template overrides (or output overrides) to alter the HTML-output of modules and components without making core hacks. For most extensions making template overrides is pretty straightforward. However, overriding the menu-module isn't. In this tutorial we will alter the module mod_mainmenu to add a CSS-class first to the first menu-item and a CSS-class last to the last menu-item. Creating the override
First of all we need to create the override itself. To do this we need to create a directory html within our template-directory and create within html another directory called mod_mainmenu: /templates/MY_TEMPLATE/html/mod_mainmenu/ Now we copy the layout-file modules/mod_mainmenu/tmpl/default.php to this new directory. In general all files within a subfolder tmpl within a Joomla! MVC-extension are layout-files. /modules/mod_mainmenu/tmpl/default.php This is the actual override. When parsing all the extensions Joomla! will use our copy instead of the original. This means we can edit this copy freely without having to worry that a Joomla! upgrade could overwrite our changes. No HTML, just PHP!Most extensions use layout-files to add HTML-code to their output. This means that the layout-file looks like a generic HTML-document with some extra PHP-code to add logic to the output. In most cases this PHP-code is also very simple - variables are printed and that's it. The layout-file of mod_mainmenu is different though. It does not contain any HTML. Instead it contains a large function through which an abstract XML-structure is parsed. Now we need to alter this function to add our CSS-classes first and last to it. First of all we need to find the part where the <ul>-tag is generated. From the <ul>-element we can check how many <li>-elements are inside the menu. And based on the number of menu-items we can calculate the first and the last element: if ($node->name() == 'ul') {
Adding our changeNow our change involves adding the logic to calculate the number of children-elements of the <ul>-tag and then loop through these children to set the proper CSS-classes. if ($node->name() == 'ul') {
That's it. Save these changes and refresh your frontend. Within the HTML-code the CSS-classes are added in the right place. |