The Definitive Guide to Drupal 7

What is a Theme Hook?

In Drupal, theme hooks refer to template files and functions that have been specifically registered via hook_theme(). This may sound scary or over-technical to non-PHP developers, but honestly it’s not. You’ve already learned about template files and theme functions, so technically you already have a pretty good grasp on theme hooks.

Whether a template file or function is implemented in core is decided on a case-by-case basis, and the criteria for making this decision is usually a balance between how likely it is to be reused by other modules, how often it is expected to change, and whether or not it makes sense for performance reasons. Template files are slightly slower than theme functions so they are not always desirable. Smaller bits of markup for things like form input elements are more efficiently implemented as theme functions, whereas larger chunks like nodes and blocks are better as a template file.

  • Both theme functions and template files exist as a way for Drupal and its modules to create output consisting of markup and variables in a way that you, the themer, can override and make it your own. They are both entirely YOUR domain, and you get the last word as to how they should look.
  • Both share the same exact theme hook. For example, a template file called node.tpl.php and a function called theme_node() share the same node theme hook. The difference is in the implementation, as both cannot be used at the same time.
  • Both can take advantage of preprocess functions, which allow you to intercept and alter variables before rendering. Using the node hook as an example, this would look like template_preprocess_node(); in your theme it would be yourtheme_preprocess_node().

You are reading content from two chapters on Theme Development from The Definitive Guide to Drupal 7, written by Jacine Luisi and published by Apress on July 19, 2011. All rights reserved.