Give your Drupal blocks a more descriptive HTML ID attribute

The information in this article applies to Drupal 5. For Drupal 6 and 7, I'd recommend just using the Block Class module.

I don't know about you, but I like my HTML ID attributes and therefore my CSS selectors to be descriptive. It makes both my HTML and CSS more readable, and lets me scan a document more effectively, locating the section I need with relative ease.

If you create a custom Drupal block the system will typically output a line of HTML which might look like this:

<div id="block-block-1" [...]

That doesn't help me very much when I have a bunch of custom blocks and I'm trying to track down a particular one. The code snippet below will change the way Drupal outputs block IDs in your templates, making them a little more palatable:

<div id="block-block-my-block-description" [...]

Step 1: Copy the code snippet below to your theme's template.php file (create one in your theme's folder if it doesn't exist). The snippet will try to calculate the new ID by looking at the block description field. If that's blank, it will revert to Drupal's standard method of calculating the ID.

function block_id(&$block) {
  $info = module_invoke($block->module, 'block', 'list');
  if ($info[$block->delta]['info']) {
    $block_id = 'block-' . $block->module . '-' . $info[$block->delta]['info'];
    $block_id = str_replace(array(' ', '_'), '-', strtolower($block_id));
    return preg_replace('/[^\-a-z0-9]/', '', $block_id);
  } else {
    return 'block-' . $block->module . '-' . $block->delta;
  }
}

Step 2: In block.tpl.php change the opening DIV tag to match the following line:

<div id="<?php print block_id($block); ?>" class="clear-block block block-<?php print $block->module ?>">

The line above is based on the opening block DIV tag from Drupal's Garland theme. If your opening DIV tag doesn't match, just make sure you change the value of the ID attribute to match.

NOTE: This article was first published on The Web Developer's Blog, which has now been discontinued.