Tuesday, July 1, 2008

Drupal CMS : how to have an image as the block title?

In Drupal, you can only have normal text as a block title. What if you hant to have an image ? There are many solutions, unfortunately, as far as I know, all of them involve customizing CSS for every block. Fortunately I'm a lazy guy, so I decided hat was too much (boring) work. Instead I found a solution which allows you to put an image directly changing the title itself, using a kind of markup. Explainations follow.




The idea is to detect if the title is a normal title or an image. If it's an image, then instead of displaying it as normal text, we want Drupal to display...well, obviously, an image! :-)

As we are limited in the title length I had to put in place a strange syntax ... but it works, at least !

Instead of a normal title, my "image" title looks like :

img=title_contactUsForm.png h=30 w=149 m=switchcalc

what does that mean ?

Well your title HAS to start with img, followed by the image filname.
h is the height
w is the width
then, to specify the path of the image, you can have either "m", "t" or "e" . They respectively mean "module", "theme" or "theme_engine" , followed by the name of the module, theme or ...theme engine. To understand how it works, please have a look at drupal_get_path function of the drupal api.


Basicaly, what the example above means is that I want to insert an image called "title_contactUsForm.png", located in the directory of the module switchcalc, whose height is 30px and width is 149px.

Now, to support this syntax, you have to customize the code of your theme's block.tpl.php.

At the begining you'll find something like :


<?php if ($block->subject): ?>
<h2><?php print $block->subject ?></h2>
<?php endif;?>


Just replace it by :


<?php if ($block->subject): ?>
<?php if (substr($block->subject,0,3)=="img") {
$tok = strtok($block->subject," ");
while ($tok !== false)
{
switch (substr($tok,0,1))
{
case "m":
$type="module";
$name=substr($tok,2);
break;
case "t":
$type="theme";
$name=substr($tok,2);
break;
case "e":
$type="theme_engine";
$name=substr($tok,2);
break;
case "w":
$imgwidth=substr($tok,2);
break;
case "h":
$imgheight=substr($tok,2);
break;
case "i":
$imgfilename=substr($tok,4);
break;
}
$tok = strtok(" ");
}

echo "<div class='title'><img src='".drupal_get_path($type,$name).$imgfilename."' height='".$imgheight."' width='".$imgwidth."' /></div>"";
} else { ?>
<h2 class="title"><?php print $block->subject; ?></h2>
<?php } ?>
<?php endif; ?>


Then this will work for every block whose name starts with "img".

Please note this code is probably not very robust if you don't enforce the syntax, so feel free to change it and make it better.

Hope it helps .

No comments: