Skip to main content

Drupal 6ers: register your theme functions! Here's how.

April 18, 2008

So now that I'm dipping into Drupal module development a bit, I ran into some 'roadblocks' that were fairly difficult to discover via default Drupal documentation.

The first thing you should do if you're starting your first Drupal 6 module, is follow along with Drupal.org's Module Development Guide for Drupal 6. That will step you through everything you'll need to know to write your first module.

However, if you're like me, and would rather fail miserably and break everything before you figure out how to do something right, you'll find that it's a bit difficult to discover how to utilize the theme layer to output content from your module. (Unless, of course, you read that tutorial above first.)

But anyways, if you're simply looking for how to register your theme functions, do this in your module:

<?
function name_of_module_theme() {
return array(
'name_of_theme_function' => array(
'arguments' => array('items' => NULL)
)
);
}

That piece of code will register your theme function, and tell Drupal's theme layer to look for the 'name_of_theme_function()' function to display content from your module. It also says that your theme function will take one argument, and that argument should be a variable defined as '$items'. You can add arguments by simply expanding that array.

Within your module, also specify a default theming function:

<?
function theme_name_of_theme_function($items = NULL) {
$output = 'hey, this is some output that gets generated when theme_name_of_theme_function($items) is called from somewhere';
return $output;
}

With this in place, your module can use the following theme function to trigger the theming:

<? theme('name_of_theme_function',$items);

This is extremely useful, because now different themes can use the following call in their template.php file to override your default theme function:

<?
nameofdifferentheme_name_of_theme_function($items){
return 'dont display that crap!' . $items;
}