Drupal: use block subject as block class name

I needed to style one block differently than the standard blocks. Now, you could argue that you can use the $block_id or $id variables in the block template but the first is a sequential number for the block in its region, the latter is a sequential number for the entire page. But if the sequence of the blocks is altered in admin/build/block then this changes.
Instead, I decided to add some simple code to the block preprocess function in template.php.
<?php
function phptemplate_preprocess_block(&$vars) {
// --- Create subject class name ---
if ($vars['block']->subject) {
$subject = strip_tags($vars['block']->subject);
$vars['block_classes'] = ' block-' .
strtolower(preg_replace("/[^A-Za-z0-9]/", "", $subject));
}
}
?>The function preg_replace() (see php.net) replaces characters outside the ranges "a-z" or "A-Z" or "0-9" with an empty string.
In the template block.tpl.php we can then simply use this as follows:
<?php
<div class="block<?php print $block_classes; ?>">
<?php if ($block->subject) { ?>
<h2><?php print $block->subject; ?></h2>
<?php } ?>
<div class="blockcontent">
<?php print $block->content; ?>
</div>
</div>
?>So if the subject is available for the block it will be used in the class name for the block's main <div>. For example, the block "Latest blog posts" will have the class name block-latestblogposts added, which can easily be used in a style sheet.
.block {
//styles for standard blocks go here
}
.block.block-latestblogposts {
//styles for the latest blog posts block go here
}But I had a block without a subject...
The previous code snippet works as long as a subject is entered for the block. Since I had a block without subject, I used a quick and dirty work-around by starting the block subject with an asterisk and removing the subject in the block pre-processor once the class name is created.
<?php
function phptemplate_preprocess_block(&$vars) {
// --- Create subject class name ---
if ($vars['block']->subject) {
$subject = strip_tags($vars['block']->subject);
$vars['block_classes'] = ' block-' .
strtolower(preg_replace("/[^A-Za-z0-9]/", "", $subject));
}
// --- Strip block subject if it starts with * ---
if ( substr($vars['block']->subject, 0, 1) == '*' ) {
unset($vars['block']->subject);
}
}
?>I needed the subject in the code to allow for the creation of the class name. After the class name is created, the subject is removed with unset().