Embed a Region in a node.tpl.php file (D5)

By default, drupal provides a number of regions to put blocks in and lets you put them pretty much anywhere in the page you want to. But, there are a few exceptions to this rule. What if you want to put a region in a node? What if you want to put a region in between a node and the comments on that node? This may not seem so easy out of the box. Let's take a look at how to put a region in a node.tpl.php file.

Let's walk through a situation where you want to put a custom region between a node and it's comments. YOu could use this to place something like a block from the Similar by Terms module right under my posting.

Start by adding a custom region called node_region using hook_regions() in your themes template.php file.

<?php
function mythemename_regions() {
  return array(
      
'left_sidebar' => t('left sidebar'),
      
'right_sidebar' => t('right sidebar'),
      
'header' => t('header'),
      
'footer_message' => t('footer'),
      
'content' => t('content'),
      
'node_region' => t('node region'),
  );
}
?>

You'll notice the same regions that come by default are defined here as well as the new node_region. This function defines all the regions, not just additional ones. In this case, you defined the same ones that come by default and just added my additional region.

This now created the node_region so you can assign blocks to in on your blocks admin screen.

Next you need to make the variable $node_region accessible in the node.tpl.php file. To do this use the function _phptemplate_variables.

<?php
function _phptemplate_variables($hook, $variables) {
  if (
$hook == 'node') {
   
$variables['node_region'] = theme('blocks', 'node_region');
  }
  return
$variables;
}
?>

This will made $node_region available in node.tpl.php files. This same concept applies for comments and most of those other non-intuitive places you may want to put a block where it isn't obvious how.

Note: This works for drupal 5. Implementing this is slightly different in drupal 6.

Drupal 6 way

wesku - September 2, 2008 - 19:22

The way you would do the same in Drupal 6 is to modify your theme.info file with regions you want to use:

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

Next you have to implement a preprocess function in your template.php file. For example:

function phptemplate_preprocess(&$variables, $hook) {
  $variables['node_region'] = theme('blocks', 'node_region');
}

This will enable you to use $node_region in your node.tpl.php file.

 
 

Drupal is a registered trademark of Dries Buytaert.