How to create template file from custom module in drupal

A Drupal theme is a set of files that defines the presentation layer. Drupal has its own way of styling data. After the data is fetched from database or other source, the data needs to be passed to several hook functions for adding additional data, markup and style.

In this article we will see how to create a template file for theming custom module data.

Step 1: Lets start with our file. The .info file defines modulename,description, version and an additional style sheet used within our module

Step 2: Now we start to work on our .module file. Here we simply create a menu callback and display some dummy content to demonstrate the theme functions.

In the above code we are implementing the hook_theme function in our module. This hook function returns an array with the themehookname that is responsible for rendering the data . In our case the function name is mytheme, it specifies the template file to be used for displaying the data, the variables array contains the parameter names to be passed to the template along with the default value.

In our example we are passing a single variable called message with NULL as default value. so to render the data we need to call the theme(‘themehookname’) ie. theme(‘mytheme’) in our case. Before the actual template gets called the preprocess function will be called which will set the value for the variable parameter.

The purpose of calling the preprocess function is, it gives the flexibility to add additional variables (i.e dynamic data). A Real time scenario would be suppose we need to add additional data or add some css classes in the core module, we can simply call this preprocess function in our custom theme or custom template and add our classes or dynamic data along with the core module. Drupal’s Theme functions reduces the need to hack the core files for customization


Step 3: Now we are going to create the actual template file. The name of the template file would be mytemplate.tpl.php, as we have specified the template name in mydons_learnthemes_theme function. The template file looks as shown below

Step 4: We can add some sample css style in our mydons.css as shown below. mydons.css looks as shown below.

Step 5: So our final output looks like this

Compatability: Drupal 7