Name Your Drupal Template Files By Node Title

Out of the box, Drupal has a really awesome cascading filename theming system. It is really easy to theme idividual content types simply by naming your file “page-contenttype.tpl.php”. But many times, I want to be able to create a bunch of “Page” content types really quickly (ex. “About Us”, “Privacy Policy”, etc) and theme it uniquely by node. Personally, I think it’s easier to be able to name your files according to the title of the node, and not by IDs, because when I come back to a project in a month, I won’t remember what “14” is referring to.

To combat that, I use this little helper hook which I drop into template.php

function theme_preprocess_page(&$vars, $hook) {
  if (module_exists('path')) {
    $alias = drupal_get_path_alias(str_replace('/edit','',$_GET['q']));
    switch($alias) {
      case "override":
        $vars['template_files'][] = "page-different-filename";
	  break;
      default:
        if($alias != $_GET['q']) {
	  $template_filename = 'page';
	  foreach (explode('/', $alias) as $path_part) {
	    $template_filename = $template_filename . '-' . $path_part;
	    $vars['template_files'][] = $template_filename;
	  }
        }
	break;
      }
   }
}

Now, by default, you can name your page template files by a hyphen-separated list phrase of the node title. So if I make a node called “About Us”, I can now theme the page by creating a template file named “page-about-us.tpl.php”. If you have a case where the default naming convention won’t work for you, simply put a case in the switch statement to case the particular page by slugged title.

  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Twitter

Comment | Trackback


Code

3 Responses to “Name Your Drupal Template Files By Node Title”

  1. Erik Says:

    February 15th, 2011 at 6:24 pm

    I don’t know if that’s what I’d call “really awesome”

  2. Frank Says:

    February 16th, 2011 at 6:10 am

    Don’t take it for granted: I’ve worked on a number of pretty massive Drupal builds – and not having to mess with the page templating system to achieve the looks I want is a testament to the flexibility and power of their system. I stand by my “awesome”-ness :)

  3. Erik Says:

    February 21st, 2011 at 7:47 pm

    Don’t misunderstand me. I didn’t mean to say that your code for template suggestions isn’t awesome, but you had referred to Drupal’s “really awesome cascading filename theming system.” But that, itself, is not awesome. I’ll admit I didn’t read the post date of this article until just now..

Leave a Reply