Creating separate page.tpl.php per content type

January 24, 2014 | 3 Comments | Submitted by Ganesan

Page.tpl.php:

  • Template file to display a page's output in Drupal
  • This file contains a combination of php and html tags
  • To render the content, we need to use the PHP variables. For list of available variables, see handbook page

hook_preprocess_HOOK():

  • Simply called as a preprocess function, defined in template.php of active theme
  • Essentially used to add/alter variables before they are rendered in the template file
  • To use, replace "hook" with module or theme name and "HOOK" with 'page','html' or 'block' as needed
  • In your case, this will be "my_theme_preprocess_page" since page template should be altered

Creating separate page.tpl.php:

Let come to the heart of the topic, by reading the above explanations you would have obtained a pinch of salt about the real scope in using page.tpl.php and hook_preprocess_HOOK.

Now do the following:

In active theme's template.php file add the below hook_preprocess_page() implementation,

function my_theme_reprocess_page(&$variables, $hook) {
  if (isset($variables['node']->type) && !empty($variables['node']->type)) {
    $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->type;
  }
}

Now page--node--article.tpl.phppage--node--page.tpl.php, etc. will be our per node tpl.php page.

Of course to be created by forking page.tpl.php, this will help you to have different page structure based on the content type. 



Comments

3 Comments

Nice and useful, thanks.

One question:
page--node--article.tpl.php, page--node--page.tpl.php, ... OR
page-node-article.tpl.php, page-node-page.tpl.php,...?

sivaji's picture

Hi,

It is page--node--article.tpl.php, page--node--page.tpl.php, ...

on D7
page--node--article.tpl.php, page--node--page.tpl.php,

On D6

page-node-article.tpl.php, page-node-page.tpl.php,