How to Create a Custom Template File in Drupal

Submitted by Daniel Henry on 06/14/2013 - 09:48:am

Drupal's theme system can be a bit intimidating the first time you step into it. I’ve found this little snippet trail to be really helpful for me to get a jump start on the process.

Step 1: Hook Theme

Use hook theme to register your function and the template that is associated with it.

  1. /**
  2.  * Implements hook_theme().
  3.  */
  4. function dm_message_theme() {
  5.   return array(
  6.     'message_template' => array(
  7.       'variables' => array(
  8.         'type' => NULL,
  9.         'vars' => array(),
  10.       ),
  11.       'template' => 'messages',
  12.       'path' => drupal_get_path('module', 'dm_message'),
  13.     ),
  14.   );
  15. }

Step 2: Call the Theme Function

You can call the theme function wherever you would like. Just use this syntax:

  1. theme('message_template', array('type' => $message->type, 'vars' => $vars));

Step 3: Pre Process Function

Chances are you will want to format your variables before going into the template file. The system automatically searches for pre-process functions with your template files name:

  1. function dm_message_preprocess_message_template(&$vars) {
  2. }

Step 4: Write the Template File

Template files should be structured. Processing should be done before calling the theme function and more complicated formatting should be done in the pre-process function. Leaving a template that looks a bit like this:

  1. <div class="message">
  2.   <div class="message-region message-region-left">
  3.     <?php if (isset($image)) : ?>
  4.       <div class="message-item-left message-image"><?php print $image; ?></div>
  5.     <?php endif; ?>
  6.     <?php if (isset($image_subtext)) : ?>
  7.       <div class="message-item-left message-image-subtext"><?php print $image_subtext;?></div>
  8.     <?php endif; ?>
  9.     <?php if (isset($image_subtext2)) : ?>
  10.       <div class="message-item-left message-image-subtext2"><?php print $image_subtext2;?></div>
  11.     <?php endif; ?>
  12.   </div>