blog-banner

Creating Separate page.tpl.php Per Content Type

  • Drupal 7
  • Drupal Planet
  • PAGE.TPL.PHP
  • TEMPLATE

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 a list of available variables, see the handbook page

hook_preprocess_HOOK():

  • Simply called as a preprocess function, defined in template.php of the 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 the page template should be altered

Creating separate page.tpl.php:

Let's 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, will help you to have a different page structure based on the content type.

Get awesome tech content in your inbox