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 />

If a function were defined as follows:<br />

function foo_spaghettify($code, $type = 'thin', $sticky = TRUE) { }<br />

Then, code that called it could just call foo_spaghettify($code) and the $type and<br />

$sticky parameters would get the default values defined in the function definition.<br />

With a single $variables parameter we have an issue. If we tried the following:<br />

function foo_spaghettify($variables = array('code' => array(),<br />

'type' => 'thin', 'sticky' => TRUE) { }<br />

And then called:<br />

$variables = array('code' => $code);<br />

$result = foo_spaghettify($variables);<br />

Then, we would discover that $variables['type'] and $variables['sticky']<br />

don't get the default value, and they are also undefined. The reason is simple; default<br />

parameter values only get used if the parameter is not specified when calling the<br />

function, but we did specify the $variables parameter, so its default is not used.<br />

So how do we solve this problem in <strong>Drupal</strong>? We have modules that define the<br />

default variables in their hook_theme functions.<br />

hook_theme<br />

A module's hook_theme is primarily responsible for specifying a few things,<br />

as follows:<br />

• The theme hooks that the module is responsible for<br />

• The type of theme implementation (theme function or template)<br />

• The theme hooks' default variable values<br />

• If the hook expects a render element instead of variables<br />

In addition to those main responsibilities, the hook_theme can optionally specify:<br />

• Which file contains the theme function or preprocess functions (if it isn't in<br />

the main module file)<br />

• A pattern to use during the auto-discovery search of a theme's overridden<br />

theme hook suggestions<br />

• Some other esoteric things you can read about in its documentation:<br />

http://api.drupal.org/api/function/hook_theme/7<br />

[ 86 ]

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

Saved successfully!

Ooh no, something went wrong!