How to theme a menu block in Drupal?

Joel picture Joel · Aug 13, 2012 · Viewed 18.7k times · Source

This should really be a basic question but I simply don't get it after hours of searching. The question is, how do I theme menu blocks in Drupal 7?

I've created three different blocks all based on the main menu. Now I want to:

  1. create unique HTML for all three blocks, that means modifing the surrounding wrapper and the <ul> and <li> that builds the menu. I wanna set special classes and remove all of the Drupal-added stuff

  2. attach different classes to the different levels within each block. One of blocks will show two levels of the menu, i.e. it will display a submenu. I want to set a special class on the for the submenu...

This seems impossible... :(

Thank you in advance for the help!!!!

Answer

davidneedham picture davidneedham · Aug 15, 2012

Theming is a tricky beast that often varies a lot depending what you need to do. Even with your very detailed description I can still say "it depends", but here are a couple steps that may help you get pointed in the right direction.

Step 1: Use a block tpl.php as suggested by Caffeine Addict. If you're not sure what to name the .tpl.php, I recommend the Theme Developer module. It's buggy, but you can use it to select an particular element and have it tell you suggestions for naming of .tpl.php files.

Outlining candidate template files from devel themer

Step 2: Use a theme / preprocess function in template.php to modify the pre-defined variables and markup. Be sure to check on the theme_menu_tree & template_preprocess_menu_tree functions on api.drupal.org for starting points. If you're using the devel module, use dpm($variables); in each of those to see what you have to work with from the start.

I hope that helps! I agree with Caffeine Addict when he says that superfish might be an alternative. You should also probably check out the menu block module for breaking out conditional sub-sections into their own blocks.