Register your theme functions in Drupal

drupal

I am new to Drupal and I am working on creating my own theme for our custom module. Can any one please help me understand how to register our theme functions or share any ideas or links that explains the process from scratch.

Best Answer

Register a theme function means implementing hook_theme in your module.

For example, if your module is called "example", then you need to have a function called example_theme in the example.module file. The theme function must return an array or you'll end up with the famous white screen of death.


In example.module:

<?php
// $Id$

// Implements hook_theme
function example_theme(){
    return array(
        'mydata' => array(

            // Optionally, you can make the theme use a template file:
            // this line references the file "mydatafile.tpl.php" in the same folder as the module or in the folder of the active theme
            'template' => 'mydatafile',

            // these variables will appear in the template as $var1 and $var2
            'arguments' => array(
                'var1' => null, 
                'var2' => null, 
            ),

        ),
        'myotherdata' => array(

            // these variables will appear in the functions as the first and second arguments
            'arguments' => array(
                'var1' => null, 
                'var2' => null, 
            ),

        )
    );
}


// If you don't want to use a template file, use a function called "theme_THEID" to create the HTML.
function theme_myotherdata($var1, $var2){
    return "<div>var1= $var1 and var2= $var2</div>";
}

In mydatafile.tpl.php:

<div>mydatafile.tpl.php was called</div>
<ol>
    <li>var1: <?php echo $var1; ?></li>
    <li>var2: <?php echo $var2; ?></li>
</ol>

You can then later call the theme function manually if needed:

 $html = theme('mydata', 'hello world', 123);
 $html = theme('myotherdata', 'hello world', 123);

In which case "mydatafile.tpl.php" and "theme_myotherdata" will receive the value "hello world" in $var1 and the value 123 in $var2.


There are many more options, like changing the name of the function, using patterns instead of a fixed name, being able to have the function in another php file or such, check out the link.


Here are a couple more ressources about theming:


By the way, you will need to rebuild the theme registry cache if you add the functions in the .module file after it has been installed, in which case you can do so by clearing the cache (one way is using the button at the bottom of the the Performances page).

Related Topic