Drupal 6: Creating your own template files for your theme

In order to promote readable and scalable themes (and modules), it’s important to plan the organization of your template files and preprocess functions. If you find yourself putting too much PHP code in a template file, you might need to move that code into a preprocess function. On the other hand, if you find yourself putting too much HTML in a function, you might need to create your own template file.

In this code snippet, I’ll show you how you can create and define your own template files to be used in your Drupal site. The first thing to do is find a section of your code that has a significant amount of HTML scattered throughout.

Let’s take this sample piece of code for example:

<?php
$html = "";
$myVar = "HTML";
$html .= "<div>HERE IS A LARGE AMOUNT OF <b>"
  . $myVar . "</b> BEING CREATED.</div>";
return $html;
?>

For this example I’m going to convert the statement that creates the HTML into its own template file. I’ll start by creating a new file in my template directory called “example.tpl.php”. I’ll then copy the following into my new file:

<div>
  HERE IS A LARGE AMOUNT OF <b><?php print $myVar; ?></b> BEING CREATED.
</div>

Notice that I had to enclose my variable in PHP tags with a print statement. This is because the template file will be treated as HTML, just like node.tpl.php or block.tpl.php.

Now we have to let our theme know that we created a template file by defining a hook_theme(). The hook_theme() function resides in the template.php file of your theme, please read more about it here. In your hook_theme() function, you return an associative array of theme implementations along with their arguments and template names.

<?php
function MYTHEME_theme() {
  return array(
    'MYTHEME_example' => array(
      'template' => 'example',
      'arguments' => array('myVar' => null),
    )
  );
}
?>

At this point you’ll have to flush your theme registry before hook_theme() is processes and your new template file is available. Once that’s done, you can use the theme() function to call your theme implementation. Let’s replace the original example with a theme() function call:

<?php
$html = "";
$myVar = "HTML";

/*
$html .= "<div>HERE IS A LARGE AMOUNT OF <b>"
  . $myVar . "</b> BEING CREATED.</div>";
*/
$html .= theme('MYTHEME_example', $myVar);

return $html;
?>

In the above snippet I used the theme() function to call my template implementation called “MYTHEME_example” and passed it one argument “myVar”. As long as you defined arguments in hook_theme(), they will be passed into your template scope. The following will be contents of the $html variable:

<div>
  HERE IS A LARGE AMOUNT OF <b>HTML</b> BEING CREATED.
</div>

Updated: