Switching Drupal tpl.php files at will: Old Switchy McTipplefep's Trick

Section:

One of the first lessons they teach you at the School of Drupal Arts, Arcane Sciences and Sorcery is that a tpl.php can have dynamically generated wildcards or "suggestions". You can see this every day drupal themes: you can simply use the "node.tpl.php" file if you want only one style for a node. Where as if you want different styles for three node types: blog, story & page, you create the following files:
  • node-page.tpl.php
  • node-story.tpl.php
  • node-blog.tpl.php
Obviously, this pattern exists far beyond nodes. For page.tpl.php, user/register can have its own tpl.php file:
  • page-user-register.tpl.php
Where as user/1/edit will be (yes -- these suggestions will remove numbers... i think... i was hung over that day in class):
  • page-user-edit.tpl.php
This may be fine and dandy if your agenda is either to build a simple drupal theme with a few exceptions, or to build manly Texas sized drupal themes with enough tpl.php files, and duplicate html code to choke a donkey. Old Switchy McTipplefep's trick is for anyone who:
  • wants 3 styles that are shared by 20 blocks
  • wants 4 possible layouts for dozens of pages in a site
  • has 12 node types, but wants them to share 3 styles
The magic happens in your theme's $theme_name . '_preprocess_' . $theme function. Below are examples for how a theme named "example" would do it.
function example_preprocess_node(&$vars) {
  $node = $vars['node'];
 // only switch for story type
  switch($node->type) {
    case 'story':
      $vars['template_files'][] = 'node-batman';
      break;
  }
}

function example_preprocess_block(&$vars) {
  // sure why not -- we'll pass our node.tpl.php file to our block
  // That's how tpl pimpin works sometimes
  $vars['template_files'][] = 'node-batman';
}