Drupal's Dynamic layouts

Submitted by AppCreator on Thu, 06/26/2008 - 12:31

One of the many things taken for granted when working with Drupal is that ability to have dynamic layouts. Different layouts for different pages, based on the blocks assigned to regions for the page.

Variables are set during page construction that can tell you how many columns are required. Which in combination with the page.tpl.php and your stylesheet can provide any number of layouts.

Default Regions from theme info file:
regions[left] = Left sidebar
regions[right] = Right sidebar
regions[content] = Content
regions[header] = Header
regions[footer] = Footer

Blocks can be assigned to those regions and variables containing the blocks will be available. For example if you assign a block to 'Left sidebar', then the variable $left will be available in your page.tpl.php. Knowing that you can check if the left column is needed in page.tpl.php, and write the column in if it is with something like:

<?php if (!empty($left)): ?>

<?php print $left; ?>

<?php endif; ?>

Now that you have the columns in your page structure you can change the widths of columns based on which ones are needed. making use of $body_classes variable which tells you additional information about the page such as node type, front, logged-in, two-sidebars, no-sidebars, sidebar-left, sidebar-right ... Information about $body_classes can be found in theme.inc function template_preprocess_page. I have started to overwrite the defaults in my own template.php files mainly to shorten the classes.

In your Stylesheet you can switch column widths based on the body classes.
body.sidebar-left #main {width:70%;}
body.sidebar-left #sidebar-left {width:30%;}

body.two-sidebars #main {width:50%}
body.two-sidebars #sidebar-right {width:25%}
body.two-sidebars #sidebar-left {width:25%}

body.sidebar-right #main {width:70%}
body.sidebar-right #sidebar-right {width:30%;}

So there you have it a layout that dynamically adjusts to the number of columns.