Extend block, so it behaves like it should

Last modified: August 26, 2009 - 23:51

I quickly extended block functionality, to meet my own requirements. There is a series of issues with the original block design, that fortunately can be addressed via template.

  • Why can't I have some intelligent ID naming for my blocks?.
  • Why can't I set a custom ID for a block, from within it's defining function?
  • Why can't I set a custom class, or whatever other attributes for a block, from within it's defining function? As it is, I can't assign it any JS events... only within it's content... this is not good.

Here is a quick solution, this should be saved as block.tpl.php in your active theme folder. Luckily enough, Drupal will take care of using it to render a block, instead of it's own (rather limited) protocol.

<?php
/*
    ADD ATTRIBUTES TO THE BLOCK
*/
// Add standard block class
$default_class = 'block'. ($block->module ? ' block-'. $block->module : '');
if (!isset(
$block->attributes))
   
$block->attributes = array();
if (!isset(
$block->attributes['class']))
   
$block->attributes['class'] = $default_class;
else
   
$block->attributes['class'] = $default_class .' '. $block->attributes['class'];

if (!isset(
$block->attributes['id'])) {
   
/*
    GIVE A READABLE ID TO THE BLOCK (instead of Drupal's useless block-module-29)
    */
    // Create a unique, yet readable, block id.
   
$block_id = $block->mobule .'-'. $block->subject;
   
// Remove invalid characters.
   
$block_id = preg_replace('/([^a-z0-9 ])/i', '', $block_id);
   
// Convert spaces.
   
$block_id = preg_replace('/ /i', '-', $block_id);
   
// Make it all lower
   
$block_id = strtolower($block_id);
   
   
$block->attributes['id'] = $block_id;
}
?>

<div <?php print drupal_attributes($block->attributes); ?>>
  <h2><?php print $block->subject; ?></h2>
  <div class="content"><?php print $block->content; ?></div>
</div>

Hopefully this will work for you as it did for me. Now I can integrate blocks in my logics, the way it should have been already a long time ago.

Cheers!

 
 

Drupal is a registered trademark of Dries Buytaert.