Drupal – Add page.tpl.php for different Content Type

In Drupal, we can determine the template files of the page which is going to be rendered. Add the following code in your template.php.

...
function <theme>_preprocess_page(&$vars) {
  // Drupal 7
  print_r($vars['theme_hook_suggestions']); exit();

  // Drupal 6
  print_r($vars['template_files']); exit();
}
...

 

Refresh the page in browser, you should get sth like

Array ( [0] => page-node [1] => page-node-184 )

 

The means Drupal will apply page-node-184.tpl.php for the rendering page, if it is not found, page-node.tpl.php will be used. So if you want to add a new template, just append new element to the $vars[‘template_files’].

The following example will add the page-<content-type>.tpl.php to the vars[‘template_files’].

...
function <theme>_preprocess_page(&$vars) {
  // Add page template for different content types
  if (isset($vars['node'])) {
    // Drupal 7
    $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;

    // Drupal 6
    $vars['template_files'][] = 'page-'. str_replace('_', '-', $vars['node']->type);
  }
}
...

 

If you have 2 content types which are named as store and convenient_store, the corresponding page templates are
Drupal 7

  • page--store.tpl.php
  • page--convenient-store.tpl.php

Drupal 6

  • page-store.tpl.php
  • page-convenient-store.tpl.php

 

Done =)

Reference: Creating Custom Content Type Page Templates with Drupal & PHP

Update @ 2013-02-25: Add Drupal 7 implementation as stated in this comment.

Advertisements

9 thoughts on “Drupal – Add page.tpl.php for different Content Type”

    1. Hi Tronno,

      The article only works for D6. For Drupal 7, use the following instead.

      function <theme>_preprocess_page(&$vars, $hook) {
        if (isset($vars['node'])) {
          // If the node type is "blog_madness" the template suggestion will be "page--blog-madness.tpl.php".
          $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
        }
        //print_r($vars['theme_hook_suggestions']);
        //exit();
      }
      

      Reference: Drupal 7 Template Suggestions

      Kit

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s