How to print a block inside a node on a Drupal 6 website

August 08, 2012 - 10:41

Blocks are regions on a Drupal website that show small but significant pieces of content. Blocks are an important component from the perspective of a Drupal website. Blocks are usually assigned to regions in a page and they are supposed to be printed on a page. However there are many instances where you might want to print a block within a content. It is not directly possible to assign a block to a region within content (node in Drupal speak) as you can do with a page. But as with everything in Drupal there is a way to do that.

Theming a node

Assigning a block to a region comes under theming. So you should have a little info on theming first. Drupal uses the PHP templating system which means that a Drupal theme consists of template files. Template files end with the extension *.tpl.php. To keep it short and simple there is a generic .tpl.php file for a page (page.tpl.php) and .tpl.php file for a node (node.tpl.php). The node.tpl.php is used to theme the content appearing in the node. For eg. the content of the pages and stories and page.tpl.php is used to theme the content in the pages which usually means most of the content around the nodes which includes blocks.

Blocks are not usually printed within nodes as it deals with only content. However there are many instances where you might want to create a block inside the content. Typically this would happen if you wanted to create a custom content type and wanted to embed a slideshow or a form inside it like creating a portfolio page.

Printing the block in node.tpl.php

To print the block within a node you have to create the block first. If you are using a module to create the block, you have to use hook_block from within that module. After creating the block you have to use module_invoke_() which is the function used to print the block within a node. This should be done within the hook_preprocess_node() function in the template.php file.

$vars['$block_variable'] = module_invoke('module_name','block','view','name_of_your_block');

As you can see the function has 4 parameters/arguments. The first one is of course the name of your module. The second parameter denotes the type of hook we are supposed to call. The third parameter describes the mode which in the present situation would be to view the module and finally the the last parameter is the machine name of the block.

The above line of code assigns the block to a variable. This can then be printed in the node.tpl.php within a suitable set of div tags for styling the block as follows:

print $block_variable;

Get Drupal updates straight to your inbox

To prevent automated spam submissions leave this field empty.

Post your comments / questions