Create a Page Template for Anything You Want in Drupal

Chris Toler

Written by Chris Toler

Custom page template designs for websites

Out of the box, Drupal provides the ability to create page templates for different pages/sections. However, its flexibility is relatively limited, in our opinion. This page on drupal.org shows the following page.tpl.php naming conventions and uses:

1. page.tpl.php (global)

2. page-front.tpl.php (front page)

3. page-node-edit.tpl.php (node edit)

4. page-node-[#].tpl.php (specific node)

5. page-node.tpl.php (nodes - global)

6. page-[internal/path].tpl.php (specific path)

This is an interesting list. While it does accommodate for quite a bit, it misses a few seemingly obvious use-cases. Now, this of course depends on your site and its needs. It may suit your purposes just fine. On the off chance it doesn’t, however, take a little trip with us down the rabbit hole and find out how to create your own page templates for literally ANYTHING you want.

Page template per content type

One of the things that’s missing from the list above is “page-content-type.tpl.php” (e.g. page-blog.tpl.php). What if you want your Blog nodes to use a different structure than your Page nodes?

In your theme’s template.php file (create it if it doesn’t exist), add the following:

<?php
...
function YOURTHEME_preprocess(&$vars, $hook) {
  global $user;
  switch($hook) {
  case 'page':
    // Check to see if the page is a node
    if ($node = node_load(arg(1)) && arg(0) == 'node') {
      $node = node_load(arg(1));
      $types = node_get_types('names');
      // Check to see if there is a valid Content Type
      if (in_array($node->type, $types)) {
        $suggestions[] = "page-node-$node->type";
        $vars['template_files'] = array_merge($variables['template_files'],
$suggestions);
      }
    }
  }
}
...
?>

Page template for any section

Or, what if you want to add a page-template for an entire section, based on the path (e.g. foo/bar/*)?

<?php
...
function YOURTHEME_preprocess(&$vars, $hook) {
  global $user;
  switch($hook){
  case 'page':
    // Check path for /foo/bar/*
    if(arg(0) == 'foo' && arg(1) == 'bar' && arg(3)) {
      $suggestions[] = "page-foo-bar-section.tpl.php";
    }
  }
}
...
?>

Just don’t forget to rebuild the theme registry if the template.php file is new, or your site won’t pick the changes up!

Chris Toler

Written by Chris Toler

Need technology experts?

Contact Us