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.

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

The theme() function would discover that the typical_hook theme hook was<br />

implemented as a template and render the corresponding typical-hook.tpl.php file.<br />

As we mentioned earlier in the chapter, the only valid<br />

characters in theme hook names are alphanumeric characters<br />

and underscores. This is true of all theme hooks, regardless<br />

of whether they are implemented as a theme function or as<br />

a template file. However, when theme() looks for template<br />

implementations, it will automatically convert any underscores<br />

in the theme hook name into hyphens while searching for the<br />

template file. For example, calling theme('user_picture',<br />

$variables) will result in the template file named userpicture.tpl.php<br />

being rendered.<br />

Also, just like theme functions, other modules can modify the variables using<br />

preprocess functions.<br />

In template files the focus is on printing out variables in various places in the<br />

markup. So for template files, the preprocess function takes on a more important<br />

role. The only difference between a theme function's preprocess functions and a<br />

template file's are the number and type of preprocess functions.<br />

The preprocess zoo<br />

When you write a theme function, its natural to pass the raw data in as parameters<br />

and generate any display-related meta-data inside the function. With a template<br />

file, that's not really possible without putting complex PHP inside the template.<br />

However, as was stated earlier, all of the PHP in a template file should be limited to<br />

just the bare minimum required to print out a PHP variable. Any processing that we<br />

need to do on the raw data parameters to ease it into print-ready variables should be<br />

done in preprocess functions.<br />

"template_" preprocess functions<br />

When a module defines a theme hook by creating a template file, that module should<br />

also create a corresponding preprocess function to set up and process any variables<br />

that are needed by the template file, but are not passed as parameters to theme().<br />

By convention, that preprocess function should be of the following form:<br />

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

The template_ prefix tells <strong>Drupal</strong>'s theme system that this preprocess function is<br />

the primary preprocessor for the theme hook's variables and should be run before<br />

any other module's preprocess function.<br />

[ 72 ]

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

Saved successfully!

Ooh no, something went wrong!