Theming blocks by type, not by region or by module name

You are here

Contact

Israel Office

+972-52-838-7222

+972-52-430-5252

Europe office

+33-695-805-004

23.04.2008
Theming blocks by type, not by region or by module name
submitted by: Zohar Stolar

Often we need to theme blocks by type (for example blue block, red block, green block), regardless of their position (e.g. their region) or the module supplying them (e.g. module & delta).
Phptemplate lets you theme a block using a template file (hereafter mentioned as simply "tpl"), following a defined naming convention. When theming a block, phptemplate will look for the right tpl in the theme directory. The possible names are nicely described in the handbook.

But what if we want to theme few blocks in the same manner and those blocks have nothing in common? They don't reside in the same region, they are not supplied by the same module, and they shouldn't have the same structure as the default block.
The only out-of-the-box solution I'm aware of, is to have a dedicated tpl for each of these blocks, which is a copy of the rest of the special blocks.
This solution however, is out of the question.

So how do you group blocks which have nothing in common, except for the need to theme them all in the same way?

Symlinks

The fastest solution is to create the needed tpl, and then link to it with symbolic links, which have the same names a for a dedicated tpl. For example, if we wanted to theme the RSS block, and the "who's online" block in the same way, we'd create the necessary tpl:
green-block.tpl.php and then link to it with two symbolic links:
block-node-0.tpl.php and
block-user-3.tpl.php
Both blocks will get the theme of green-block.tpl.php

This method is easy to maintain - you just symlink files together, and you get the right design.

_phptemplate_variables

_phptemplate_variables is a function which lets us add or modify variables which become available for our tpl files. We usually use this function in template.php.
We can use it to add a template file, which will be added to the list of suggestions, when phptemplate is looking for the right tpl:
<?php
if ($hook == 'block') {
$identifier = $vars['block']->module . '-' . $vars['block']->delta;
switch ($identifier) {
case 'node-0':
case 'user-3':
$vars['template_file'] = 'green-block';
break;
}
return $vars;
}
?>

This way opens the road for programatically assign tpl files to non related blocks.

... Are there any other evident methods I am not aware of?

Add new comment