Page Template Suggestions per Node Type

Sometimes its useful to have a page.tpl.php template per node type. While you can have a node-[type].tpl.php be default in Drupal 6, the same does not apply to page level templates.

To add these template suggestions to your theme simply add the following code to template.php, replacing themeName with the name of your theme.

Drupal 6

<?php
function themeName_preprocess_page(&$vars, $hook) {
  if (isset(
$vars['node'])) {
  
// If the node type is "blog" the template suggestion will be "page-blog.tpl.php".
  
$vars['template_files'][] = 'page-'. str_replace('_', '-', $vars['node']->type);
  }
}
?>

Drupal 7

Note the slightly different syntax for D7 template suggestions - they use two hyphens instead of one:

<?php
function themeName_preprocess_page(&$vars, $hook) {
  if (isset(
$vars['node'])) {
 
// If the node type is "blog" the template suggestion will be "page--blog.tpl.php".
  
$vars['theme_hook_suggestions'][] = 'page__'. str_replace('_', '--', $vars['node']->type);
  }
}
?>

Last updated 3rd December, 2010 - 3:35pm

Authored by Jeff Burnz on