Where do I create PHPTemplate variables in Drupal theming?

Here’s some code, which you can put into your template.php file. It demonstrates how to insert code into that file, so you can make new variables available to page, node and comment template sites/default/files. Examples of where this is useful are shown in the snippet below.

<?php
function _phptemplate_variables($hook, $vars = array()) {
  switch (
$hook) {
    case
'page':
     
// code relating to variables for page templates here
      // EXAMPLE - is the current user logged in?
     
$vars['logged_in'] = ($user->uid > 0) ? TRUE : FALSE;
      break;

    case
'node':
     
// code relating to variables for node templates here
      // EXAMPLE - on front page teasers, make a comment count var using a query
     
if ($vars['teaser'] && $vars['is_front']) {
       
$vars['comment_count'] = db_result(db_query("SELECT comment_count
          from {node_comment_statistics} where nid = %d"
, $node->nid));
      }

      break;

    case
'comment':
     
// code relating to variables for comment templates here
     
break;
  }
 
// anything that you require for all the above, put outside the switch statement
 
return $vars; // this passes the variables back to the relevant template
}
?>

Blog Tags: DrupalThemesPHP

Comments

I’ll be posting a few articles that link back to this one (“interesting examples” :) The first one should hit the blog later today.

Add new comment