Drupal 7 inline menu item theming

Today I had to do a fairly common Drupal theming task, turning a menu block into a set of inline links. In pictures, I needed to go

from this: inline-links-2 to this:     inline-links-1

Since I usually do module dev and similar tasks for Koumbit, I was aware that Drupal already has a built in class for lists containing links that would display my links inline. That class is “links inline”. Unfortunately I wan’t sure how to go about changing those values at the theme layer. So I visited the API page of theme_menu_tree()hoping for some inspiration, and found some in this comment by wgsimon. A custom theme can override the theming of a specific menu item in Drupal 7 by using the pattern THEME_menu_tree__MENU_NAME().

I added the following code to the template.php of my theme, to make both the standard user menu and our custom menu for anonymous users use Drupal’s built in theming for inline links:

/**
 * Make the user menu inline
 */
function customtheme_menu_tree__user_menu($variables) {
  return '<ul class="links inline clearfix">' . $variables['tree'] . '</ul>';
}
 
/**
 * Make the anonymous user menu inline
 */
function customtheme_menu_tree__menu_user_menu_anonymous_($variables) {
  return '<ul class="links inline clearfix">' . $variables['tree'] . '</ul>';
}

Just replace customtheme with your themes name and change the menu names to use this yourself.

For the language switcher I did something similar, after consulting locale_block_view() in the api and seeing that the language switcher block uses theme('links__locale_block', $variables); to provide its content. The template.php based override looked like this:

/**
 * Theme the language switcher link as inline
 */
function customtheme_links__locale_block($variables) {
  array_push($variables['attributes']['class'], 'links', 'inline', 'clearfix');
  return theme('links', $variables);
}

So I learned that that the theme_function__object_name pattern will work for any theme function called this way. I am certain this must be specified somewhere in the Drupal API documentation.

At this point my menus looked like this:inline-links-3

The last step is more theme specific. In my case I moved the contents of <div class="region region-header"> and surrounding markup in my page.tpl.php to before the logo, and inserted the following CSS rules into the appropriate files:

.region-header .block {
  display: inline-block;
  margin-bottom: 0;
}
 
.region-header {
  text-align: right;
}

The result: inline-links-4

Obviously, there is still some work left before the final product looks like the design, but my main concern up until this point was to avoid cluttering up my CSS with code that is already present in the Drupal core.

One thought on “Drupal 7 inline menu item theming”

  1. Just what I needed!

    Saw this on The Weekly Drop on a day that I had to theme a menu to be inline – perfect timing! and really helpful.

Comments are closed.