Different page templates depending on URL aliases

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.

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']) {
         
$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;
}
?>

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']) {
     
$suggestions = array();
     
$template_filename = 'page';
      foreach (
explode('/', $alias) as $path_part) {
       
$template_filename = $template_filename . '-' . $path_part;
       
$suggestions[] = $template_filename;
      }
    }
   
$vars['template_files'] = $suggestions;
  }
}
?>

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.