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 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
}
?>
Posted by Nik - February 11th, 2008 at 9:54pm






Any interesting examples ?
Posted by Alan F. on Monday, 25 February, 2008 - 11:24.I’ll be posting a few articles that link back to this one (“interesting examples” :) The first one should hit the blog later today.
Posted by Nik on Tuesday, 26 February, 2008 - 15:34.Post new comment