Tag Archives: API

Finding The Path To Your Drupal Theme

Ever needed to reference a file in your Drupal theme? For example, an image from your page.tpl.php file, or a JavaScript file?

You can hard code the path, which might be something like:

/sites/all/themes/mytheme/images/myimage.jpg

Or, with a little bit of PHP, you can use Drupal’s built in path_to_theme() function. This function will print out the path to your Drupal theme from the root directory.

So, in your theme you might have this image, but instead of writing:

<img src=”/sites/all/themes/mytheme/images/myimage.jpg” alt=”My Awesome Image” />

You could write:

<img src=”/<?php print path_to_theme(); ?>/images/myimage.jpg” alt=”My Awesome Image” />

At first glance it is slightly longer and might seem like more effort to do. Think of it a bit differently though. What if you want to rename your theme, or use your theme on a different domain name? You will need to change the hardcoded path. By using Drupal’s path_to_theme() function, it will dynamically figure out the path to your theme directory for you.

We can then take this a bit further with Drupal’s base_path() function. This particular function returns the path to the base Drupal installation. If you have it installed in the root directory of your hosting account, then this will simply be a /.

The real benefit of this is if your Drupal installation is in a different directory. For example, /drupal. If this is the case, then your hard coded path would be /drupal/sites/all/themes/mytheme/images/myimage.jpg the path_to_theme() function will still only return /sites/all/themes/mytheme though, and the browser will not be able to find your image. The reason for this is that it only determines the path from the base installation directory of Drupal. So, to make sure your theme is truly dynamic and capable of dealing with this, you would use something like this:

<img src=”<?php print base_path() . path_to_theme(); ?>/images/myimage.jpg” alt=”My Awesome Image” />

Now if you have Drupal installed in a sub-directory called Drupal, this would actually return the full path we need: /drupal/sites/all/themes/mytheme

One thing to remember if you use this is that the path_to_theme() function doesn’t put in a trailing / or start off with a / so you will need to put these in before adding in the rest of your files location. Comparatively though, base_path() does add a / both before and after the path. So if you use it, you will not need to prefix it with a /.

This works in Drupal 5 and 6, and I believe is going to continue to function the same way in Drupal 7, so your themes will be all set to work on any server without needing to adjust the file paths. Give it a try!

You can also have a look at these functions in the Drupal API documentation: