Path To Theme In A Module

Photo of Greg Harvey
Fri, 2008-10-03 16:54By greg

I'm currently working on a multi-site Drupal installation. There is one theming module shared by all instances which exposes some key blocks and views they all require. During development, this was built on the initial site, so occasionally you will find something like this in the module:

function load_my_image() {
$path = base_path().
drupal_get_path('theme', 'my_theme').
'/images/my-image.gif';
return $path;
}
?>

That works fine for as long as 'my_theme' exists, but what if it doesn't on another instance using this module?

No problem, we thought - just use path_to_theme() like this:

function load_my_image() {
$path = base_path().
path_to_theme().
'/images/my-image.gif';
return $path;
}
?>

Wrong! You cannot, must not, EVER use path_to_theme() outside of either a theme function or template.php. If you do, it will not return what you expect it to return. Instead of the path to your theme, you'll get a seemingly arbitrary path to the last invoked module. Because modules are not supposed to have anything to do with themes, you have no business calling path_to_theme() in a module anyway.

In the end we moved the images the module needs to the module's own directory and called them like this instead:

function load_my_image() {
$path = base_path().
drupal_get_path('module', 'my_module').
'/images/my-image.gif';
return $path;
}
?>

This is logically and conceptually correct, because the module does not depend upon the existence of images in a theme which may not be there.

The only additional caveat is to say this also should be in a theme function, so other developers can override the image location in their template.php files, if they so wish, where it *is* valid to use path_to_theme().