Drupal - Adding content to the sidebar without using a block

When creating a new Drupal module, I'd been trying to add a couple of links to a sidebar when viewing a user's details. I could of done this using a block but that would rely upon the block being setup to only appear on the user's page, and would also include all the markup that comes with a block. This is how I got around all that.

When creating a new Drupal module, I'd been trying to add a couple of links to a sidebar when viewing a user's details. I could of done this using a block but that would rely upon the block being setup to only appear on the user's page, and would also include all the markup that comes with a block. This is how I got around all that.

First thing I did was include the code that will add any code set to appear in the sidebars actually into the sidebar. This is done by the _phptemplate_variables function in template.php in your skin's directory. I already had a _phptemplate_variables function so I just added a new case for page's in my existing function so it looked something like this:

function _phptemplate_variables($hook, $vars = array()) {  switch ($hook) {    case 'node':      // removed for clarity      break;    case 'page':      foreach (array('left','right') as $region) {        $vars[$region] = drupal_get_content($region);      }      break;  }  return $vars;}

All this does is make sure the code that the code is only run for pages and then get any content set for the region and add it to the relevant template variables, it then returns the variables. This is the code that does the business:

foreach (array('left','right') as $region) {  $vars[$region] = drupal_get_content($region);}

If you wanted to include more regions that just the left and right you could add those into the array. Now in your module you can use the drupal_set_content function to put content into either the left or right region like this:

$output = l('some link text','node/1234');drupal_set_content('left', $output); 

This link should now appear in the left sidebar whenever the function this is in is called. I included something similar in my hook_user for my module to include a link that will only appear on my user pages.

About the Author

Steve Temple, Technical Director and co-founder of Gibe

Steve is Gibe's technical director and super brain behind the development of our major projects. With over 28 years of commercial experience, Steve is an expert in .NET, Umbraco and Microsoft technologies. Steve is also an Umbraco Certified Master and Microsoft MCSD