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.

[ 75 ]<br />

Chapter 3<br />

Process functions are extremely useful when you have meta data that is likely to be<br />

manipulated by other modules or themes and you wish to delay the rendering of the<br />

meta data until just before the template file itself is rendered.<br />

In the preceding code example, the template_preprocess() function creates a<br />

$classes_array variable that holds an array of classes to be used on the wrapping<br />

div in the template file. <strong>Module</strong>s and themes can easily add classes by simply adding<br />

an additional array element from inside their preprocess function, as follows:<br />

$variables['classes_array'][] = 'extra-savoir-faire';<br />

Themes can use much simpler array manipulation functions in order to remove or<br />

alter classes.<br />

// Search for the bogus class and return its array key<br />

// location. If not found, array_search returns FALSE.<br />

// Remember that 0 is a valid key.<br />

$key = array_search('bogus', $variables['classes_array']);<br />

if ($key !== FALSE) {<br />

// Alter the class.<br />

$variables['classes_array'][$key] .= '-dude';<br />

}<br />

// Or remove the no-soup class.<br />

$variables['classes_array'] = array_diff($variables['classes_array'],<br />

array('no-soup'));<br />

In addition to the $classes_array variable, the template_preprocess()<br />

function also creates $attributes_array, $title_attributes_array, and<br />

$content_attributes_array variables which are used for HTML attributes on the<br />

outermost wrapping div, the title's heading tag, and the content's wrapping div,<br />

respectively. You'll see each of these variables used in the typical-hook.tpl.php<br />

example, given earlier in the chapter.<br />

After modules and themes are given an opportunity to alter these variables, the<br />

theme system uses the template_process() function to render those arrays into<br />

a simple string, as follows:<br />

function template_process(&$variables, $hook) {<br />

// Flatten out classes.<br />

$variables['classes'] = implode(' ', $variables['classes_array']);<br />

// Flatten out attributes, title_attributes, and content_attributes.<br />

$variables['attributes'] = drupal_attributes(<br />

$variables['attributes_array']);<br />

$variables['title_attributes'] = drupal_attributes(<br />

$variables['title_attributes_array']);<br />

$variables['content_attributes'] = drupal_attributes(<br />

$variables['content_attributes_array']);<br />

}

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

Saved successfully!

Ooh no, something went wrong!