23 August 2012

Creating your own template files that you can use in your modules in Drupal 7. Template files are for separating HTML from PHP. This tutorial shows you how to create and use tpl.php files. Template machine names can not start with numbers.

Define your template:

Source code viewer
  1. /**
  2.  * Implements hook_theme().
  3.  */
  4. function HOOK_theme() {
  5. $theme = array();
  6.  
  7. // Unique identifier for template.
  8. $theme['HOOK_template'] = array(
  9. // Define variables you wish to pass on.
  10. 'variables' => array(
  11. 'url' => NULL,
  12. 'text' => NULL,
  13. ),
  14. // tpl.php file name with or without directory, don't forget to use dashes.
  15. 'template' => 'templates/HOOK-template',
  16. );
  17.  
  18. return $theme;
  19. }
Programming Language: PHP

Use your defined template in PHP code:

Source code viewer
  1. $variables = array(
  2. 'url' => 'http://browse-tutorials.com/',
  3. 'text' => 'A great collection of tutorials',
  4. );
  5. echo theme('HOOK_template', $variables); // unique identifier
Programming Language: PHP

Your template file (HOOK_template.tpl.php):

Source code viewer
  1. <strong><?php echo $text; ?></strong>
  2. <a href="<?php echo $url; ?>"><?php echo $url; ?></a>
Programming Language: HTML