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

We've actually already discussed most of the work flow of theme(). There's only one<br />

aspect we haven't yet seen. So far, we've only called theme() with a simple string<br />

passed to its $hook parameter. However, we can actually pass more complex data to<br />

it and make use of the theme system's theme hook suggestions.<br />

Theme hook suggestions<br />

So re-using theme hooks in various places in our code is a good thing, of course.<br />

However, one problem you'll encounter is that theme functions lose context when<br />

a theme hook is re-used. For example, theme_links() has no idea if it's theming<br />

node links or comment links, which makes it difficult to style them differently.<br />

Fortunately, we can provide context to the theme system by providing a theme hook<br />

pattern as its first parameter:<br />

[base hook]__[context]<br />

The parts of the pattern are separated with a double underscore since some theme<br />

hooks (like user and user_profile) could be confusing if we were to use a single<br />

underscore to delineate the parts of the pattern. In fact, we can provide additional<br />

contexts if needed, as follows:<br />

[base hook]__[context]__[even more context]__[don't get crazy]<br />

So how does this work and how does it help? In <strong>Drupal</strong> 7, we theme the<br />

node's links by calling theme('links__node', $vars). So theme() will use a<br />

theme_links__node() function if one has been provided. However, if one doesn't<br />

exist, it will use theme_links(). This allows us to know the context based on the<br />

theme function we are implementing. A more complex example is when <strong>Drupal</strong> 7<br />

themes the node's contextual links; it calls theme('links__contextual__node',<br />

$vars). So, theme() will search for a theme_links__contextual__node(), then<br />

for theme_links__contextual(), and lastly theme_links(), shortening the<br />

pattern by one unit of context each time.<br />

The theme hook pattern is an easy-to-use method of providing context, but some<br />

contributed modules need to provide more complex lists of context than the simple<br />

string pattern can provide. For this reason, an array of possible hook suggestions can<br />

also be passed to theme(). For example, both Views and the Menu block module<br />

use this method. While theming trees of menus, Menu block provides the following<br />

array to theme:<br />

$hook = array(<br />

'menu_tree__menu_block__' . $delta,<br />

'menu_tree__menu_block__' . $menu_name,<br />

'menu_tree__menu_block',<br />

[ 83 ]

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

Saved successfully!

Ooh no, something went wrong!