Theming Drupal blocks dependent on the region

The other day I was working with the menu_block module (http://drupal.org/project/menu_block), and I was trying to theme the block dependent on the region it was assigned to, to get sets of different looking menus for different page types. The hooks that are in menu_block don’t use any region info, just block ID, block name, and whether you are actually using the menu block module. So, here is an easy way to pass the block region into other dependant hooks:

Firstly, override the theme_block function, and create a global variable called $_current_region. It’s also a good idea to set the variable to null just before closing the function. Here is the standard theme_blocks function overridden in template.php:

function phptemplate_blocks($region) {
    // pass the current block region so we can use it in other hooks later
    global $_current_region;
    $_current_region = $region;

    // start of standard theme_block hook
    $output = '';

    if ($list = block_list($region)) {
        foreach ($list as $key => $block) {
            $output .= theme('block', $block);
        }
    }

    // Add any content assigned to this region through drupal_set_content() calls.
    $output .= drupal_get_content($region);

    // set region to NULL seen as we have now passed it on
    $_current_region = NULL;

    return $output;
}

So now, we can make that variable available in other functions, for example theme_menu_tree, and theme_menu_item, and you can style the menus dependant on the region. Here is theme_menu_tree:

function phptemplate_menu_tree($tree) {
    global $_current_region;

    switch ($_current_region) {
        case 'front_menu':
            return $tree;
            break;
        case 'content_page_menu':
            return '<ul class="subnavigation">' . $tree . '</ul>';
            break;
    }
}

Filed under  //   blocks   drupal   theming