Drupal 7: How to Make a Drupal Theme Function in a Module

This is intended as a simple reminder for all of those out there who find making a drupal theme a bit confusing at times.
There are three main steps that all work together.

1) hook_theme which adds an array of callbacks and their arguments to the theme registry. You need to put this in your sites/all/modules/mymodule/mymodule.module file to rebuild the theme registry before it would be added.

function mymodule_theme($existing, $type, $theme, $path) {
  $theme = array(
    // This is in the mymodule.module file.
    // example theme template register
    // for sites/all/modules/mymodule/templates/mymodule_theme_name.tpl.php
    'mymodule_theme_function_name' => array(
        'variables' => array('node' => NULL, $param2 =>NULL),
        'type' => 'module',
       ),
  );  
  return $theme;
}// function 

2) The themable function itself which starts with theme_ followed by the function name that was added to the registry with hook_theme

// The $vars paramiter is an array of passed 
// variables corresponding to the 'variables' 
// key in the the above hook_theme() function.
function theme_mymodule_theme_function_name( $vars ){
... code here ...
// Return a string that contains the rendered representation of the data.
 return $output; 
}//function

3) Then call the function,

 theme('mymodule_theme_function_name', $whatever_argument );

which actually calls the function.

It is important to remember all three of these or the theme will not work.

2 thoughts on “Drupal 7: How to Make a Drupal Theme Function in a Module


  1. The $theme array in the first example isn’t closed out completely. Otherwise, this just saved me hours of research. 🙂 Thank you for all of these write-ups!

    I must have bookmarked half your site by now!


  2. Thanks, Josh! I fixed it. : )
    Im so glad this site has been helpful.
    I see on your “tweets” you are into electronics.

Leave a Reply

Your email address will not be published.