Categories

Thursday, February 18, 2010

Changing Page.tpl Based On Node Type in Drupal

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/<YOUR THEME NAME>).

To begin:

  1. Locate your template.php file in your theme directory.
  2. 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']->typeinstead of $vars['template_files'][] = 'page-' . $vars['node']->type;

Share on:

Synopsis

If you use Drupal you may encounter the difficulty in setting up individual page.tpl.php for different node types.