How do I create templates in my custom module? 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.
hook_theme is your friend, it allows you to modularize your markup in two ways:


Allows you to define a template file for your markup.
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' =&gt; array(
       'variables' =&gt; array('variable1' =&gt; NULL, 'variable2' =&gt; NULL),
       'template' =&gt; '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:

&lt;div class="some class"&gt; &lt;?php print $variable1; ?&gt; &lt;/div&gt;
&lt;div class="class2"&gt; &lt;?php print $variable2; ?&gt; &lt;/div&gt;


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' =&gt; $variable1, 'variable2' =&gt; $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.)