Exercise 52 Use Random Colors for Blocks

If you wanted to have each block on the page have a randomly chosen color, this would be a great opportunity to add the logic for choosing the color. Naturally, you could do this directly in the block.tpl.php file, but that would make the file harder to read for your graphic designer, who doesn't care how you determine the color, only that it is available in a nice, clean variable to be applied inside the template.

First, add the following _phptemplate_variables function to the template.php file in your theme. If the template.php file doesn't exist, create it (make sure to begin the file with <?php):

function _phptemplate_variables($hook, $vars) { switch ($hook) { case 'block': // generate a random color string like #26295d $color = '#';

for ($i = 0; $i < 3; $i++) { $r = dechex(rand(0, 255)); $color .= strlen($r) < 2 ? '0'.$r : $r;

// add the $color variable to the $vars array $vars['color'] = $color; break;

return $vars;

Next, update the block.tpl.php file in your theme with the following code, which uses the new $color variable to create a border around each block (changes are highlighted):

<div class="block block-<?php print $block->module; ?>" id="block-<?php print $block->module; ?>-<?php print $block->delta; ?>" style="border:5px solid <?php print $color ?>;">

<h2 class="title"><?php print $block->subject; ?></h2> <div class="content"><?php print $block->content; ?></div> </div>

Now when you access your site, every block should have a border with a randomly chosen color.

Manipulations at this point in the code are useful mainly for adding decoration or elements that are external to your site's logic. Most of the page execution code has been run by the time _phptemplate_variables gets called, which means it is quite limited in its possibilities. Furthermore, keep in mind that this is the theme for your site, which, by definition, should concern itself exclusively with visual elements and layout. Nevertheless, for tasks like using random colors for blocks, it is a useful place to make customizations.

0 0

Post a comment