background image
HomeRecent PostsDrupalSearchTagsRSSContactAboutAccount

Creating dynamic theme layouts based on the contents of your regions

Eric.London's picture

When creating a theme, it's important to keep your layout flexible in order to avoid wasted space. Here's a quick tutorial to show you how to vary theme layouts based on the contents of a region. Consider a common layout that contains 3 columns: sidebar_left, content, and sidebar_right. If the sidebar_right region did not have any blocks assigned to it, you could conserve valuable space by revising your theme layout using CSS and theme variables.

The first thing to do is add a variable to the page.php.tpl scope of your theme. In your template.php file, add a function called _phptemplate_variables. The following code checks the currently assigned variables to see if html has been assigned to the regions. If the region is empty, a variable will be passed to the theme containing CSS class selectors.

<?php
function _phptemplate_variables($hook, $vars=array()) {
  switch(
$hook) {
    case
'page':
     
$layoutClasses = array();
      if (!
$vars['sidebar_right']) $layoutClasses[] = 'noSidebarRight';
      if (!
$vars['sidebar_left']) $layoutClasses[] = 'noSidebarLeft';
     
$vars['layoutClasses'] = implode(' ', $layoutClasses);
      break;
  }
  return
$vars;
}
?>

Next, in your page.tpl.php, locate the div in your layout that your like to conditionally change. Add the following code to add the CSS class selectors as necessary.

<?php
<div id='layoutContent' class='<?php print $layoutClasses; ? >' >
 
BLAH BLAH BLAH
</div>
?>

Last, you can add CSS to revise your layout. In this case, I'll change the width of my divs.

#layoutContent {
  width: 500px;
}

#layoutContent.noSidebarRight {
  width: 750px;
}

#layoutContent.noSidebarLeft {
  width: 750px;
}

#layoutContent.noSidebarLeft.noSidebarRight {
  width: 1000px;
}