18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 3<br />

Here's an example that should make this concept a bit clearer. This is an actual code<br />

snippet from <strong>Drupal</strong>'s block preprocess function. In each page region, all of the<br />

blocks in the region get a variable whose value alternates between "odd" and "even".<br />

These values can be used to create zebra-striped styling, that is, alternate styling on<br />

every other block in a region.<br />

function template_preprocess_block(&$variables) {<br />

// We store all block counters using drupal_static().<br />

$block_counter = &drupal_static(__FUNCTION__, array());<br />

// All blocks get an independent counter for each region.<br />

if (!isset($block_counter[$variables['block']->region])) {<br />

$block_counter[$variables['block']->region] = 1;<br />

}<br />

// Generate the zebra striping variable.<br />

$variables['block_zebra'] = ($block_counter[$variables['block']-<br />

>region] % 2) ? 'odd' : 'even';<br />

}<br />

// Increment the region's block count.<br />

$block_counter[$variables['block']->region]++;<br />

The PHP logic in this function is directly related to the display of the block and<br />

not to the general business logic of this data. So, it doesn't make sense that the<br />

block module would calculate that meta data before calling theme(); the meta data<br />

clearly belongs to the display logic, which is why it's placed in the block module's<br />

preprocess function.<br />

Multi-hook preprocess functions<br />

In some rare circumstances, you may need to alter or provide some variables for<br />

all theme hooks. In fact, <strong>Drupal</strong>'s theme system does provide some variables to all<br />

templates; the preprocess function that provides these variables is both a "template_"<br />

preprocess function and a multi-hook preprocess function. Multi-hook preprocess<br />

functions are simply functions that don't have a _HOOK suffix added to their name<br />

and are run for every single template file. Their name is of the following form:<br />

[module]_preprocess(&$variables, $hook)<br />

Obviously, there can be a big performance hit if a module needlessly implements<br />

a multi-hook preprocess function. If you're contemplating writing one, if at all<br />

possible, consider writing several preprocess functions that target the specific<br />

hooks you need instead, rather then hit all hooks.<br />

[ 73 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!