Using .tpl Template Files in Custom Drupal 7 Modules

Advertisement

Advertisement

In Drupal 7 the theme and template layer can easily be over complicated, but this is the quickest and most effective way in my opinion to get started using template files in your custom modules. Get in the habit of using a template file instead of putting pieces of HTML inside your module code. This system is pretty flexible and you can create a template for a small item or for a whole page.

There are a couple important steps

  • Define your theme function so Drupal knows how to handle it. Drupal needs to know what template file you want to use and you can set default variables if necessary. You may also specify a path if you don't want to put the template in the root of your module.
  • Optionally, you can create a preprocess callback to manipulate and variables between they finally make it to the template.
  • Call theme() to get the rendered HTML content.
/** Create a theme function that maps your custom name to a template */
function mymodule_theme()
{
  return array(
    // Name to be called with theme(). theme('my_custom_gallery', $images)
    'my_custom_gallery' => array(
      // Default variables
      'variables' => array(
        'image_urls' => null,
      ),
      // Which .tpl.php file to use my-custom-gallery.tpl.php
      'template' => 'my-custom-gallery',
      'path' => drupal_get_path('module', 'tumbly') . '/templates')
    )
  );
}

/** Optional callback to manipulate and set variables */
function mymodule_preprocess_my_custom_gallery(&$vars) {
  // This variable will be available in the template file as $custom_value
  $vars['custom_value'] = 'Hello!';
}

/** Finally, call the theme function from anywhere to get the rendered contents */
function mymodule_test_page()
{
  $images = node_load_multiple(array(1, 2, 3));
  $output = theme('my_custom_gallery', array('images' => $images));
  return $output;
}

You must also create the actually template file. In this case it will be my-custom-gallery.tpl.php

<ul>
<?php foreach ($images as $image): ?>
  <li><img src="<?=$image[LANGUAGE_NONE][0]['value']?>" /></li>
<?php endforeach; ?>
</ul>

Advertisement

Advertisement