Drupal: One <body> attributes function to rule them all

So we figured out a neat Drupal trick at work today – it’s a way to add some very useful attributes to the tag in your Drupal 6 themes.

I wanted to have the tag in our theme templates to have a set of hooks that I could use for CSS and JavaScript. Ideally, I wanted 1. A unique ID for every page 2. A class based on the section the page was in 3. A class based on whether there was sidebar content or not (left & right)

So, the resulting tag would look something like this:

<body id="page-pagename" class="section-sectionname sidebars">

Which would make it much easier to do page-specific or section-specific CSS or JavaScript.

(The sidebars thing is taken directly from Garland – which is helpful in it’s own right.)

This has been addressed before – for Drupal 5, but it didn’t really work for Drupal 6. Specifically, the home page of a site wouldn’t get the correct resulting ID/class.

So, with some tweaking, and the help of a more knowledgable coworker, here is a function that adds all of the desired attributes to any given page’s tag.

First, in you page.tpl.php file, add this function call to the body tag, like so:

<body<?php print phptemplate_body_attributes($is_front,$sidebar_left, $sidebar_right); ?>>

Then, make the corresponding function in your template.php file, like this:

function phptemplate_body_attributes($is_front,$sidebar_left, $sidebar_right) {
//originally shared at http://drupal.org/node/32077, plus the sidebar piece is from Garland
  if ($is_front) {
    $body_id = 'front';
    $body_class = 'front';
  else {
    // Remove base path and any query string.
    global $base_path;
    list(,$path) = explode($base_path, $_SERVER['REQUEST_URI'], 2);
    list($path,) = explode('?', $path, 2);
    $path = rtrim($path, '/');
    // Construct the id name from the path, replacing slashes with dashes.
    $body_id = str_replace('/', '-', $path);
    // Construct the class name from the first part of the path only.
    list($body_class,) = explode('/', $path, 2);
   $body_id = 'page-'. $body_id;
   $body_class = 'section-'. $body_class;
  // Use the same sidebar classes as Garland.
  if ($sidebar_left != '' && $sidebar_right != '') {
    $sidebar_class = 'sidebars';
  else {
    if ($sidebar_left != '') {
      $sidebar_class = 'sidebar_left';
    if ($sidebar_right != '') {
      $sidebar_class = 'sidebar_right';
return " id=\"$body_id\" class=\"$body_class  $sidebar_class \"";

Ta day! Now your tag looks something like this:

<body id="page-test-page-1" class="section-testpages sidebars">

Pop open your CSS, rev your jQuery, and go to town!

Read MoreLeave a comment