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.

Chapter 3<br />

Second, the theme function will only have a single parameter, as follows:<br />

function theme_THEME_HOOK_NAME($variables) {…}<br />

The theme function variables are an associative array containing the pieces of data<br />

we wish to markup and any options we want to pass to the function. It may seem<br />

extremely odd not to use multiple parameters and PHP's ability to specify default<br />

values for each parameter. In fact, previous versions of <strong>Drupal</strong> did use multiple<br />

parameters. We'll see why <strong>Drupal</strong> now only uses one parameter in just a moment<br />

when we talk about preprocess functions.<br />

For an example of a $variables array, let's look at how the DocBlock of the<br />

theme_item_list() function defines it:<br />

• Items: An array of items to be displayed in the list. If an item is a string, then<br />

it is used as is. If an item is an array, then the "data" element of the array is<br />

used as the contents of the list item. If an item is an array with a "children"<br />

element, those children are displayed in a nested list. All other elements are<br />

treated as attributes of the list item element.<br />

• Title: The title of the list.<br />

• Type: The type of list to return (e.g. ul, ol).<br />

• Attributes: The attributes applied to the list element.<br />

The items and title keys hold the actual data, and the type and attributes keys<br />

are options that specify how to build the item list.<br />

Third, the theme function should return a string that contains the rendered<br />

representation of the data. This is usually a string of HTML, but some theme hooks<br />

return other types of themed markup. For example, theme_syslog_format returns<br />

a simple string with pipe-separated data values for use in a *NIX syslog error log.<br />

That's it! As you can see, theme functions have very simple requirements and in<br />

every other way are standard PHP functions.<br />

The major difference between most functions and theme functions is that you should<br />

never call theme functions directly. It may be tempting to take your data and call<br />

theme_item_list($vars) directly, but you should instead call theme("item_list",<br />

$vars). This method of calling theme functions indirectly ensures that themes are<br />

able to override any module's default theme function (or template). It also allows the<br />

theme() function to work additional magic, including allowing other modules to alter<br />

the theme function's variables before they are used.<br />

[ 67 ]

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

Saved successfully!

Ooh no, something went wrong!