HOWTO: Write Cleaner tpl.php Files

The PHPTemplate system in Drupal is a powerful theming system. However, because it is written in PHP it is easy to abuse since it is possible to directly inject PHP logic into the templates. This often creates the effect of HTML-IN-PHP which is not good.



HTML-IN-PHP:

 

print '

'. $title .'

';
?>

 

PHP-IN-HTML:


print $title ?>

 

Which do you think a themer who understands HTML/CSS will understand better? Of course the second, because it is mostly HTML and the themer can modify the HTML tags quite easily.

Conditional Statements

Another example of this is with logic statements.

HTML-IN-PHP:

global $user;
if (
$user->uid) { ?>

 

You are now logged in!



} ?>

 

PHP-IN-HTML

global $user; ?>
if ($user->uid): ?>

 

You are now logged in!



endif; ?>

 

See how the second example is easier to read? It's also broken up into small pieces that a themer can move around quite easily. Having open and closing braces for an if statement is really hard to follow. But if(conditional): and endif; statements are easy to read, and "chunkify" or "modularize" the text in a clear way.

 

if ($test == TRUE): ?>



endif; ?>

 

PHPTemplate variables

The last thing that can make your life and the themer's life easier is to pass variables to the template files using phptemplate_variables. A tpl.php really should be mostly simple conditional statements and print statements. If you have PHP code spanning multiple lines or are working with arrays or something, you can probably pull that code out of the tpl.php and put it in template.php.

Example Node.tpl.php with too much PHP

if ($node->field_related[0]['nid']) {
 
$related_cck_node = node_load($node->field_related[0]['nid']);
  print
'
';
}

?>

 

Why is all that logic in the tpl.php? You can move that out into template.php.

Using Template.php to add variables to your tpl.php files

function _phptemplate_variables($hook, $vars = array()) {
  switch(
$hook){
    case
'node':
      if (
$vars['node']->field_related[0]['nid']) {
       
$related_cck_node = node_load($vars['node']->field_related[0]['nid']);
       
$vars['related_cck_link'] = l($related_cck_node->title, 'node/' . $related_cck_node->nid);
      } 
      break;
  }
  return
$vars;
}

?>

 

Now the node.tpl.php file will get a new variable called $related_cck_link which you can easily print out.

Example Node.tpl.php file with logic removed

if ($related_cck_link): ?>
 

endif; ?>