Give your Drupal blocks a more descriptive HTML ID attribute

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.

<?phpfunction 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.

I have +4 years of quality experience in Front-End Developer from India. I have worked on HTML5, CSS3, JSON, XML, Angular, jQuery, WordPress, Bootstrap for developing tabled, table-less, responsive and non-Responsive web-sites. I have worked on many complicated and easy design in some top level web development companies in India while also working on independent projects as freelancer.

Got something to say? Go for it!