I've created a custom module that has a bunch of PHP functions whose main purpose is basically to output HTML. For example:

function showRecentActivity($tid, $recordStart, $count){
    //do some db_select stuff to get an array of node IDs...

    foreach($nids as $nid){
        $node = node_load($nid);

        //now that we've loaded the node, 100 lines of if, echo, etc. will follow in order to output the HTML to the page

Perhaps you can already see the problem. While echoing HTML is fine for small pieces of markup, constructing full pages with echo statements is horrible to code, maintain, and very bug-prone.

Obviously what is needed is a pre-defined template file, written in HTML with just small places for echoing the necessary PHP variables. Just like my theme's template files.

But I have no idea how to do this with my custom module.

1 Answer 1


hook_theme is your friend, it allows you to modularize your markup in two ways:

  1. Allows you to define a template file for your markup.
  2. Allows you to define a theme function.

No matter which way you go, you will call for the markup the same way. so lets say you wish to modularize markup for recent activity. You will do the following in your custom module:

function custom_module_theme() {
   return array(
     'activity' => array(
       'variables' => array('variable1' => NULL, 'variable2' => NULL),
       'template' => 'custom-module-name-recent-activity',

You will create custom-module-name-recent-activity.tpl.php in your module directory where you will have $variable1 and $variable2

Your custom-module-name-recent-activity.tpl.php will look something like this:

<div class="some class"> <?php print $variable1; ?> </div>
<div class="class2"> <?php print $variable2; ?> </div>

And then from your module when you have done your processing and have established $variable1 and $variable2 (you can pass as many as u want), you will simply do:

theme('activity', array('variable1' => $variable1, 'variable2' => $variable2));

Hope this helps, I wonder now if I should have linked to some tutorial. But hey its Saturday :)

(And if you are using Drupal 6, change 'variables' to 'arguments' in the code above.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.