Working on a client site today, I came across a requirement to put a line-break in a menu item. I checked out the Drupal.org website, but there wasn’t much in there apart from fixes by people who were hacking core, so I had to work it out myself.

Here’s the requirement; My client’s site looks like a book, and we need to make sure that second-level menu items do not span across the spine of the ‘book’. In this case, they did;

 

The obvious solution is to enter a line-break into the definition of the menu item. That doesn’t work, because the HTML code is simply echoed to the screen. It is, however, part of the solution. Select site building->menus, and edit the appropriate menu by adding <br /> where you want the menu to break;

 

 

 

When you view your menu, you’ll see the <br /> appear as part of the text – not the result we want, just yet.

 

 

Now we need to start programming. We’re going to override the theme_menu_item_link function.

In your theme folder, you should have a file called template.php. If you don’t, you can create an empty file with that name. Add the following code into template.php (if you already have content in that file, put the following code at the end of the file);


function phptemplate_menu_item_link($link) {
if (empty($link['localized_options'])) {
$link['localized_options'] = array();
}

$link['localized_options']= array('html'=>true);
return l($link['title'], $link['href'], $link['localized_options']);
}

How it Works

The magic happens on the line

$link['localized_options']= array('html'=>true);

where we tell the routine to render correctly any html code inside the menu title.

Save the file, then clear the theme cache (this is where the admin module comes in incredibly useful). Your menu will now show the line breaks correctly;

 

 

 

Extra Credit

Full marks to anyone who noticed that this trick will allow *any* html code inside menu title definitions. For example, <em>, <strong>,  etc. – will all work. Use this power responsibly!

Alternative Method

An alternative method is to use CSS to define the menu items as a set maximum width – longer menu titles will then automatically wrap to the next line. If the user is quite knowledgeable, this is an acceptable method, but the technique on this page gives the site content editors a modicum of control over the display of their menus – exactly the result we were aiming for.