Merge multiple _phptemplate_variables functions

Last modified: March 11, 2009 - 06:36

Many PHPTemplate theme snippets, and some contributed modules, require you to add a _phptemplate_variables function to your theme's template.php file. Unfortunately, if you want to use more than one such module or snippet, or if your theme already contains a _phptemplate_variables function, you can't simply add another one - you have to merge the two functions. If you don't know PHP very well, this may seem like a daunting task.

Here is a simple recipe for merging multiple _phptemplate_variables functions into one. You don't need to know PHP; just copy and paste, and change some names as described below.

  1. Put all the necessary _phptemplate_variables functions into your template.php file, and change all their names from _phptemplate_variables to something else. For example, _phptemplate_variables_taxonomy_snippet, _phptemplate_variables_page_title_module etc. If there's already a _phptemplate_variables function in the theme, change its name too - e.g. _phptemplate_variables_garland_theme. Make sure not to give any two functions the same name.
  2. Create a new _phptemplate_variables function. This will be the master function that will combine all the variables from the other functions. Here is what it should look like:
    <?php
    /**
    * Call all our custom _phptemplate_variables_* functions and merge the results into a single array.
    */
    function _phptemplate_variables($hook, $vars) {
     
    $funcs = array(
       
    // These are the names of our custom functions.  Add more below as needed.
       
    '_phptemplate_variables_taxonomy_snippet',
       
    '_phptemplate_variables_page_title_module',
       
    '_phptemplate_variables_garland_theme',
      );
      foreach (
    $funcs as $func) {
       
    $vars = array_merge($vars, $func($hook, $vars));
      }
      return
    $vars;
    }
    ?>
    Copy the above code into your template.php and change the function names to the ones you actually used.
  3. Later, if you want to add yet another _phptemplate_variables function, you can easily do so by giving it a new name, and adding that name to the list.
 
 

Drupal is a registered trademark of Dries Buytaert.