Emulating preprocess theme functions in Drupal 5

Submitted by Larry on 16 December 2007 - 9:37pm

Drupal 6 introduced the concept of a theme preprocess function. In short, it allows themes, theme engines, and even modules to step into the theming process and manipulate the variables that get sent to a template. It replaces the older, clunkier _phptemplate_variables() function from Drupal 5's phptemplate templating engine, but serves much the same purpose.

While we can't backport all of that new functionality, it is possible to greatly simplify _phptemplate_variables() in Drupal 5 in a way that looks a lot like Drupal 6. Specifically, we can break up _phptemplate_variables() into separate functions that act like a theme's preprocess functions in Drupal 6.

To get that simplification, simply specify your _phptemplate_variables() function in template.php like so:

<?php
function _phptemplate_variables($hook, $vars) {

  $function = 'phptemplate_preprocess_'. str_replace('-', '_', $hook);
  if (function_exists($function)) {
    $function($vars);
  }

  return $vars;
}
?>

First, we ensure that the theme hook is in a format that can be used as part oa function name, and build the name of what the preprocessing function would be called. The if it exists, we call it with the $vars array. Note that we do not accept a return value from the preprocessing function. Instead, in the called function, we accept the parameter by reference like so:

<?php
function phptemplate_preprocess_page(&$vars) {
  // Manipulate the $vars array here.
}
?>

Now we can, in the theme, step into any template file's variable building process add, remove, or modify variables to be sent to the template just by declaring the appropriate function. Although it doesn't actually give us any new functionality, it is easier to read and maintain than a giant switch statement in _phptemplate_variables() and will also be easier to upgrade to Drupal 6 later.

(This post has been reposted to drupal.org for better archiving, but I decided to post it here as well for people who don't watch for newly added book pages.)