Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto output HTML from drupal module the nice way

this may be basic, but i just started using Drupal (6 btw).

I'm building a module, and got a callback that is supposed to return some html. I could just do something like this:

function myModule_myFunction(){
    $r = '';
    $r .= '<h1>'.$variable.'</h1>';
    return $r;
} 

But I'd rather seperate logic and presentation, and put this in a seperate file, or something. HTML in strings is ugly!

What's the 'drupal' way to do this? It doesn't have to use the theme system as far as I'm concerned.

like image 439
Simon Epskamp Avatar asked May 06 '11 08:05

Simon Epskamp


2 Answers

The theme system is the drupal way to do that.

First check if there isn't already a theme function that you can use, there are many that allow to output data as table, lists, images and much more.

If there is not, you need to...

  1. Declare a new theme function with hook_theme(). Prefix it with your module, something like yourmodule_something.

  2. Create a theme function (or a template), a theme function must be prefixed theme_, so something like function theme_yourmodule_something().

  3. Make sure to clear all caches so that Drupal knows about your theme function.

  4. Call the theme function with theme(): theme('yourmodule_something', $argument1, $argument2):

More details can be found on the linked documentation pages.

like image 171
Berdir Avatar answered Nov 04 '22 19:11

Berdir


hook_theme is first used to define templates and functions for themed output.

Then, use those templates or theme functions to output any markup, e.g, to call theme_my_content or my-content.tpl.php with a couple of parameters, you can call:

theme('my_content', $param1, $param2);

like image 28
David Thomas Avatar answered Nov 04 '22 20:11

David Thomas