Adding A Class To A Drupal Theme For Logged In Users

I was working on a Drupal theme recently which required a number of different elements to be present on a number of different pages, but only for logged in users.

Using a little PHP I was able to add a class of 'in' to the body which would only appear in the html when a user was logged in.

To do this, just find the opening <body> tag in your page.tpl.php file, and add in the code below.

<body<?php global $user; ?><?php if ($user->uid): ?> class="in"<?php endif; ?>>

Then, you'll be able to write a general rule for logged out users, such as:

body {
background: #fff;
}

And a more specific rule for logged in users, such as:

body.in {
background: #000;
}

5 comments

1
Jan HeynenOctober 27th 2007 @ 02:07PM

How simple can things be?
Great post!

Jan

2
GuestOctober 29th 2007 @ 08:07PM

Pretty cool. Anyone have any examples where this would be useful? I know that the Zen theme comes with this as well.

3
BrianNovember 14th 2007 @ 04:33PM

This seems like a slick and simple solution, but isn't there a potential security risk to making the $user variable global? I've seen this example in several other places, but no one has addressed the security angle.

4
MichaelGuestMay 25th 2008 @ 06:21PM

do you know what i would need to do to allow loged in users the ability to see a "form" that has been written in html? It's a form that allows the user to log into there email address and right now i have to re direct the user to another site.

5
LaurenceMay 27th 2008 @ 01:04PM

Hi Michael, where is the form exactly?

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options