18.10.2016 Views

Drupal 7 Module Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Drupal</strong>’s Theme Layer<br />

Preprocess functions<br />

Now we're starting to see the real flexibility of the theme system. Preprocess<br />

functions allow one module to alter the variables used by another module when it<br />

calls a theme hook. So if some code passes data to theme() for a particular theme<br />

hook, preprocess functions will be called to alter the data before the actual theme<br />

hook implementation is called. The following steps are carried out:<br />

1. Code calls theme('hook_name', $variables).<br />

2. theme() calls preprocess functions for hook_name.<br />

3. Preprocess functions modify variables.<br />

4. theme() calls actual implementation for hook_name with modified variables.<br />

All preprocess functions take the form of:<br />

[module]_preprocess_[theme hook name](&$variables)<br />

So if the foo module wants to alter the variables for the item_list theme hook, it<br />

could define the function as follows:<br />

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

// Add a class to the list wrapper.<br />

$variables['attributes']['class'][] = 'foo-list';<br />

}<br />

Notice that the $variables parameter is defined with an ampersand in front of<br />

it. That's PHP notation to pass the parameter by reference. Instead of getting a copy<br />

of the variables, the foo_preprocess_item_list() function will get access to the<br />

actual $variables which is later passed to the theme function implementation. So<br />

any modifications that the preprocess function makes to the $variables parameter<br />

will be preserved when those variables are passed to the theme function. That's<br />

the reason our example foo_preprocess_item_list() function doesn't return<br />

anything; its work is done directly on the original $variables.<br />

This is extremely handy for module developers as it allows all sorts of integration<br />

with other modules. Since the variables parameter is a mix of data and options,<br />

modules can alter both the raw data and change the way data will be rendered. This<br />

can be as simple as one module needing a special class for use in its JavaScript code<br />

and adding that class to another module's themed content by appending to the $var<br />

iables['attributes']['class'] array, or can be more complex interactions like<br />

the i18n module translating the language used in blocks.<br />

Imagine we've built a retro module that integrates GeoCities and we want to replace<br />

all links to a user's profile page with a link to the user's GeoCities homepage. We can<br />

do that relatively easily with a preprocess function.<br />

[ 68 ]

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

Saved successfully!

Ooh no, something went wrong!