Different page templates depending on URL aliases

Last modified: September 13, 2009 - 09:50

The list of "template suggestions" for a template can be modified in your template.php file. The following snippet will add page template suggestions for each level of URL alias for the current page. That allows you to, for example, define page-music.tpl.php template which would apply to every page under 'music' path / logical directory. (This information is of particular importance to users of pathauto module who want to create, say, a landing page using a different tpl.php file.)

Drupal 5 version:

<?php
function _phptemplate_variables($hook, $vars = array()) {
  switch (
$hook) {
    case
'page':
   
     
// Add page template suggestions based on the aliased path.
      // For instance, if the current page has an alias of about/history/early,
      // we'll have templates of:
      // page-about-history-early.tpl.php
      // page-about-history.tpl.php
      // page-about.tpl.php
      // Whichever is found first is the one that will be used.
     
if (module_exists('path')) {
       
$alias = drupal_get_path_alias(str_replace('/edit','',$_GET['q']));
        if (
$alias != $_GET['q'] && $alias == $_REQUEST['q'] ) {
         
$suggestions = array();
         
$template_filename = 'page';
          foreach (
explode('/', $alias) as $path_part) {
           
$template_filename = $template_filename . '-' . $path_part;
           
$suggestions[] = $template_filename;
          }
        }
       
$vars['template_files'] = $suggestions;
      }
      break;
  }
 
  return
$vars;
}
?>

Note for Zen theme users: If you are creating your own ZEN subtheme under Drupal 5, implement the D6 snippet instead of the D5 version.

Drupal 6 version:

<?php
function phptemplate_preprocess_page(&$vars) {
  if (
module_exists('path')) {
   
$alias = drupal_get_path_alias(str_replace('/edit','',$_GET['q']));
    if (
$alias != $_GET['q']) {
     
$template_filename = 'page';
      foreach (
explode('/', $alias) as $path_part) {
       
$template_filename = $template_filename . '-' . $path_part;
       
$vars['template_files'][] = $template_filename;
      }
    }
  }
}
?>

Variations
The following are a couple of variations on this idea.

Change only a CSS class in a page template. Works for making changes in CSS that don't need a different template

<?php
   
if (module_exists('path')) {
       
$alias = drupal_get_path_alias($_GET['q']);
       
$class = explode('/', $alias);
        print
'<div class="page page-'.$class[0].'">';
    }
?>

Limit changes for a specific node type:

<?php
     
// (...)
     
if(arg(0)=='node') {
         
$vars['template_files'] = 'page_' . $vars['node']->type;
     }
    
// (...)
?>

 
 

Drupal is a registered trademark of Dries Buytaert.