Styling menu block's menu links in Drupal 7

Mikkel R. Lund picture Mikkel R. Lund · Mar 9, 2012 · Viewed 8k times · Source

I'm trying to style a block in Drupal 7 and I'm having a very hard time figuring things out!

I've used the menu_block module to get all links from the main menu. It produces a block with links in a ul, which I would like to theme as divs for each menu tree.

The styling itself should be easy, but I'm really struggling with finding the theme hook/template filename that I should use to style it.

I've tried to hook into theme_menu_tree and theme_menu_link, but they theme way too many places, and I can't see what I'm styling. I've tried menu-tree--menu-block--main-menu.tpl.php, but the variables are nothing like what I need.

My thought is that I need to style the $content variable in block.tpl.php, but I can't figure out how to do it for a specific block. Where should I hook in, if I want to style the menu points when the block (block type) is display (in the footer)?

Answer

Clive picture Clive · Mar 9, 2012

I think the easiest (not necessarily the best) place to do this in hook_block_view_alter()

function MYMODULE_block_view_alter(&$data, $block) {
 if ($block->module == 'menu_block') {
    // Extract the links from the available data
    $links = element_children($data['content']['#content']);
    $content = '';

    // Loop through the links and build up the required output.
    foreach ($links as $link) {
      $content .= '<div class="something">' . l($link['#title'], $link['#href']) . '</div>';
    }

    // Assign the new output to the block content...done :)
    $data['content'] = $content; 
  }
}

The Devel module and it's handy dpm() function are your best friend here...they'll let you examine any PHP variable in a nicely structured format in the standard messages area. If you don't already have it installed I'd advise doing so, it's an absolute must for Drupal development.

Don't forget to clear Drupal's caches once you've implemented that hook or the system won't pick it up.