Amitav Roy

Blog on web and travel

How to use hook_theme and hook_node_load in Drupal 7

Posted on 10 Aug 2011 by Amitav Roy

How to use hook_theme and hook_node_load in Drupal 7
function example_node_load($nodes, $types) {
     foreach ($nodes as $node) {
        $node->myvar = theme('myvar',array(
            'mysite' => "http://www.amitavroy.com",
        ));
    }
}

What are we doing here: We are using the hook_node_load to insert a variable myvar to the main $node object when the node is loading. The code from line number 3 to 5 tells Drupal that it needs to add a variable myvar to the $node object using the theme ‘myvar’ and I am passing a variable to the theme function ‘mysite’ which has the link of my website.

So, now we use the hook_theme() function.

function example_theme() {
    return array(
         'myvar' => array(
             'template' => 'myvar',
         )
    );
}

As per line number 4 of this function, Drupal knows that the variable ‘myvar’ which we are inserting to the $node object should be rendered using the template ‘myvar’. Now, this is a convention. The template name i.e. ‘template’ => ‘myvar’ should be same as the name of the variable i.e. on line 3.

Once this is done, we can create a myvar.tpl.php file inside the module folder and handle how the variable will be rendered.

<?php
/*
 * This tpl will be used to render the myvar variable.
 * $mysite will be available because we passed the variable in hook_node_load().
 */
?>
<div class="my-site clearfix">
    <p><a href="<?php print $mysite ?>"><?php print $mysite ?></a></p>
</div>

<div class="clearfix"> </div>

This is a standard way of doing things the Drupal way. I could have easily printed this in the node tpl. But, somehow custom codes in the node.tpl.php is not a very good idea. Especially if your site has quite a few node tpls.

Plus in this fashion other module have control over how this variable will behave and themer’s life will be a lot easy because if there is any styling changes required, they just have to look for one tpl to modify.