Hi there,

I'm trying to output themed content to a page and I've been trying to read up on the theme() function and how it works. As I understand, it provides a method to generate themed HTML. That's exactly what I want. Now, what I don't understand is how I pass it the HTML or the variables I want so that the HTML is generated. What's the $hook parameter? Is it a .tpl.php file? How do I structure this file so that the HTML is displayed in the content section of the page? Can someone explain the theme() function in a very simple way?

Thanks,

Comments

nevets’s picture

In simple terms, hook_theme() registers theme hooks while theme() invokes theme hooks. Using the theme layer (Drupal 7.x) shows what you need to do as a developer.

Ambimind’s picture

Hi Hydem,

I'd like to suggest the following approach:
Your initial focus on theme() is misplaced. In Drupal 7 you never have to directly deal with it(even though it is ultimately doing the work of wrapping your data in html tags - based on your orders).

Render Arrays/Renderable Arrays
should be your main focus.
Basically, these arrays contain specially named keys(by convention(#theme, #theme_wrapper...) + user defined(#yourdata)) which serve as instruction for drupal_render(), which executes theme() for you.

With this out of the way, the much simplified process is like this:
1 - In our module file eg.mymodule.module - you need to define a mymodule_theme() function.
This hook is expected to return an array. Here you must tell drupal if you want to wrap your data via a php function or a php.tpl file, and amongst other things, define the name(s) of the keys, within a renderable array, with which drupal will populate $variable. Most importantly, the name of your function/tpl.php is defined here.

2 - Actually implement the process of wrapping your data with html tags. If you decide on a php function then that function must be defined in your module as follows: theme_"the name you defined in hook_theme()". If you decide on a tpl.php file , you you must create this file(which has its own special syntax). You do not create both.

3 - In your page_callback() function or hook_page_alter(), hook_node_view() etc - you have to create the array, which will look something like this, in simplest form:
(#theme => "function/tpl.php name", #mydata => "some data, likely an array")
So, in the case of a page callaback you would: return $build['myRenderArray'] = array(...);