cgp
cgp

Reputation: 41381

Drupal: How do I invoke a template in a module?

I've got some non-node data in a custom module of mine and I would like to invoke a template to display the data. This template may get reused for email output, and I would like to basically just bootstrap Drupal and use the template as needed.

I thought I could just do something like:

$html = theme('verysmallsnippet', $my_fancy_data_structure);

...then create a verysmallsnippet.tpl.php file in active theme folder and then expect Drupal to find the template file and evaluate the template with the arguments passed to the theme function. Is this a vast over-simplistic interpretation of how the template engine works -- or do I need to setup the theme registry first? Or What?

I looked at this question, as well as the theme documentation, and I'm a bit lost.

Upvotes: 2

Views: 407

Answers (1)

Henrik Opel
Henrik Opel

Reputation: 19441

Yup, slightly over-simplistic ;)

For a better introduction than the API doc you linked, start with the Theming Guide, and for your specific need, check Using the theme layer (Drupal 6.x).

In order for your example to work you need to tell the theme registry about your template by implementing hook_theme():

function yourModule_theme($existing, $type, $theme, $path) {
  $items = array();
  $items['verysmallsnippet'] = array(
    'arguments' => array('my_fancy_data_structure' => array()), // Change array() to a fitting default
    'template' => 'verysmallsnippet',
  );

  return $items;
}

You can define more details in that hook, but this is the minimum you need in order to get a template file used (the engine will add the 'tpl.php' part for your when looking for the file).

NOTE: You need to trigger a rebuild of the theme registry every time you add or change a hook_theme() implementation, otherwise your changes will not take effect.

Upvotes: 3

Related Questions