Thursday 9 December 2010

Changing page.tpl based on node type

Via here

If you use Drupal you may encounter the difficulty in setting up individual page.tpl.php for different node types. The is a simple solution to this problem but requires a few lines of code in your template.php file, found in your theme directory (/sites/all/themes/).

To begin:
Locate your template.php file in your theme directory.
At the bottom of your template.php file enter the following code:

function phptemplate_preprocess(&$vars, $hook) {
switch ($hook){
case 'page':
// Add a content-type page template in second to last.
if ('node' == arg(0)) {
$node_template = array_pop($vars['template_files']);
$vars['template_files'][] = 'page-' . $vars['node']->type;
$vars['template_files'][] = $node_template;
}
break;
}
return $vars;
}
The customizations can be seen in Devel along the lines of
page-node-1.tpl.php -> page-story.tpl.php -> page-node.tpl.php -> page.tpl.php.

If you have to use the forums feature of Drupal you may want to prevent a name clash by implementing:
$vars['template_files'][] = 'page-nodetype-' . $vars['node']->type;
instead of 
$vars['template_files'][] = 'page-' . $vars['node']->type;

No comments:

Post a Comment