Drupal coder

Theme variables available to all Drupal template files

When writing themes there's a few values we frequently need to access in our templates. I'm thinking about stuff like "is the user logged in", "is the user an admin", "what is the theme directory" (for referencing images etc)?

The good news is that all these and a few more are available in all template files. Here's a listing of what variables are available and how you can add your own.

What variables are available?

$zebra
In the case of multiple renderings of a template in one request, this indicates if this is an odd or even invocation. The value is odd or even. Perfect for generating stuff like zebra tables etc.
$id
In the case of multiple renderings of a template in one request, this indicates which rendering this is (1st, 2nd, ...).
$directory
The path of the theme directory. Same as path_to_theme. Example: sites/all/themes/my_theme
$is_admin
Indicates if the user has the access administration pages permission set (user_access('access administration pages'))
$is_front
Indicates if the current request is the front page (drupal_is_front_page()).
$logged_in
Indicates if the current user is logged in.
$user
Contains the user object of the current user.

These variables are all added using the template_preprocess function which you can find in includes/template.inc.

How to add your own variables?

You don't have to stick with this list of variables but can add your own. You can do this on multiple levels: module, theme engine, theme, subtheme, ... This is a done using a preprocess function which doesn't mention the theme hook it wants to preprocess (like my_theme_preprocess(&$vars)).

You can find out how to do this in the documentation for the theme function in the Drupal API.

May 14, 2010Drupal, theming

Comments

Davy,

Thank you for this information, which is not easy to find on the drupal.org site!

One clarification: I believe that these variables are set in /includes/theme.inc, not /includes/template.inc in Drupal 6.x.

Hey there,

These links might also come in handy:

Greets y'all!
Joris_Lucius

Are those variables the same for all drupal versions (d5, d6, d7)??

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.

More information about formatting options