Implementing Preprocess and Process Hooks
Preprocess functions are implemented by creating a function that is named in a certain way. Listing 16–4 shows an example of this naming convention.
There are four points to consider in naming these functions:
- The hook of a default implementation, usually created by a module, is “template.” In all other implementations, the hook is replaced by the system name of the module or theme implementing it.
- Which stage of the process do you want to affect? There are two options: the preprocess, which runs first, or process, which runs after all of the preprocess functions have been executed.
- The theme hook matches the theme hook as defined in
hook_theme(), which is ultimately output using either a theme function or a template file.
&$variablesparameter contains data needed by the theme function or template file rendering it. Since preprocess functions run before templates are rendered, you can make all sorts of changes and additions to its contents.
Listing 16–5 illustrates what a preprocess implementation for a default theme hook looks like, using template_preprocess_node(), which creates variables for the node.tpl.php template file as an example. This function resides in node.module along with a hook_theme() implementation, node_theme(), where it defines “node” as a theme hook.
Theme and Module Implementations
Both modules and themes are able to use preprocess functions in the same way, and a given theme hook can have many preprocess implementations, originating from both modules and themes. This introduces the opportunity for conflicts to occur, so keeping that in mind and knowing the order in which these functions run is important. Preprocess implementations from modules run first, and implementations by themes run last. When dealing with base and subthemes, the base theme will run first and the subtheme will run last. A good way to remember this is that the active theme always wins.
Preprocess functions implemented by Drupal core and modules reside in various files, such as
theme.inc, and many others, while preprocess functions implemented by themes always reside in
As an example, implement a preprocess function for a theme called “dgd7” for the node theme hook. As shown in Listing 16–6, you simply place a function in template.php beginning with the theme name (the implementing hook), followed by _preprocess_ and the theme hook, which in this case is “node.” Finally, you pass in the
&$variables parameter by reference (the & before the $ indicates a variable being passed by reference).
The code in Listing 16–6 is all that’s needed, along with a quick cache clear, for Drupal to pick up your preprocess function and run it before rendering a node. Now the fun can begin!