Sunday, March 25, 2012

Drupal : give body tag a unique id depending on page path


Hello Developers, Today's tip title may be strange and need some clarification so i will first explain the title. When you use Drupal for development you may need to make different style for each page. To do so, you should have a unique ID for each page.
Today's tip will use the page path as an ID for the body.

1- open your template.php file.
2- find the following statement :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3- paste the following code just before that statement :

<?php
  $uri_path = trim($_SERVER['REQUEST_URI'], '/');
  $uri_bits = explode('/', $uri_path);
  if ($uri_bits[0] == '') {
    $body_id = 'front';
    } else {
    $body_id = str_replace('/','-', $uri_path); // use dashes to replace slashes in the URI
    }
  $body_id = 'page-'.$body_id; // add 'page-' to the front of the id
  $vars['body_id'] = $body_id;
?>
4- Inside the body tag, put the following identifier :
id="<?php print $body_id ?>"

so that your body tag will look like that :
<body id="<?php print $body_id ?>" <?php if (!empty($body_classes)) { echo 'class="'.$body_classes.'"'; } ?>>

AND ... That's it :)

That code in step 3 creates a variable that trims the path of your node, and converts the slash separator to dash separator, then put the path in a variable, that you can use as ID for your page.





No comments:

Post a Comment