Check sidebars from the node template

To read information about sidebars in a node template (node.tpl.php) in Drupal 7, you need to set the data in your theme_preprocess_page() function (in your theme’s template.php), where the sidebar info is made available by Drupal:

/**
 * Implementation of template_preprocess_page().
 * Let node template know about sidebars.
 */
function mmh_shared_preprocess_page(&$variables) {

  // Let node template know about sidebars.
  if (isset($variables['page']['content']['system_main']['nodes'])) {
    foreach ($variables['page']['content']['system_main']['nodes'] as $key => $value) {
      if ($value['#node']) {
        $have_sidebar_first = false;
        $have_sidebar_second = false;
        if ($variables['page']['sidebar_first']) {
          $have_sidebar_first = true;
        }
        if ($variables['page']['sidebar_second']) {
          $have_sidebar_second = true;
        }
        $variables['page']['content']['system_main']['nodes'][$key]['#node']->sidebar_first = $have_sidebar_first;
        $variables['page']['content']['system_main']['nodes'][$key]['#node']->sidebar_second = $have_sidebar_second;
      }
    }
  }

}

Then, in your node.tpl.php, you have a boolean available to tell you whether the first or second sidebar is set:

<?php
  if ($node->sidebar_first) {
    // do stuff
  }
  if ($node->sidebar_second) {
    // do stuff
  }
?>

Note that there’s probably a better place to set this sidebar data, because it’s not really a property of the nodes, but for the sake of time I did it this way. The take away point is that you must sort it out in the page preprocess.

Last modified: 21/02/2014 Tags: ,

This website is a personal resource. Nothing here is guaranteed correct or complete, so use at your own risk and try not to delete the Internet. -Stephan

Site Info

Privacy policy

Go to top