How to create custom regions in node.tpl.php in Drupal 6

| | 2 min read

Drupal allows very fine grained control over how content is presented to the end user. The presentation layer is abstracted beautifully and cleanly designed hooks allows for moving data from the logic layer to the presentation layer. The template file that handles the basic page layout of every drupal site is page.tpl.php and the different regions available for a given theme are all available as HTML elements in page.tpl.php. Another important template file is node.tpl.php which decides how nodes are presented to the end user. Normally the content of nodes go into regions inside page.tpl.php and so does blocks and panels. But what if you want to have regions inside the display area of nodes? What if you want to use blocks to display content inside nodes? The answer is simple - template preprocess is the key.

First let us define the region in the theme info file. Open the info file in your theme folder.
If no regions[] are defined you will have define all the default regions in the info file explicitly if you want to add new custom regions. Copy and paste the following default regions (as of Drupal 6) into the file

regions[left] = Left sidebar
regions[right] = Right sidebar
regions[content] = Content
regions[header] = Header
regions[footer] = Footer

Now add the declaration of your brand new region. Suppose you plan to use cool_node_region as the name of the region. Note that the right side of the equal sign is the human readable name of the region that you are going to see at admin/build/blocks

regions[cool_node_region] = Cool Node Region

If you already see regions[] variables, all you have to do is to add your new region. Then go ahead and add your custom region to the node.tpl.php. Create the HTML layout and add the php code to output the content of the region into the layout. In our example you will have to create something like the following somewhere in node.tpl.php

<div class="cool-node-region"><?= $cool_node_region; ?></div>

Remember to set appropriate css classes and ids so that you can use these to style the content in these regions via your stylesheet and not have to edit your template files again.

Create the preprocess_node function in template.php file in your theme folder

/**
* preprocess hook to add variables to the node.tpl.php
*/
function theme_preprocess_node(&$variables) {
$variables['cool_node_region'] = theme('blocks', 'cool_node_region');
}

Rebuild your theme registry and presto you are done. To rebuild your theme registry you can use the devel module or just go to admin/build/themes and save the form without making any changes. You can verify that your new region is active by going to admin/build/blocks.