Drupal 7 – Add module paths to theme registry (theme suggestions for modules)

Drupal allows for “theme suggestions” which allows one to add extra theme templates to your theme and Drupal will automatically find them and use them, but this does not work if you want to have your templates in a module directory. (http://drupal.org/node/1089656)

Now the problem/process is that Drupal only does an automatic find of theme templates and functions using the functions “drupal_find_theme_templates & drupal_find_theme_functions” when it invokes the _theme_process_registry on a templating engine, this can be seen in the “hook_theme” implementation of phptemplate (phptemplate.engine), this means that the find is done at the lowest “theme” level only, (probably for better performance reasons, I have not looked into it).

What I learnt from this is.

  • If the variable “theme_hook_suggestion” exists then it will take preference over ALL others (check around line 1118 theme.inc)
  • The basic workflow for a theme is to first run _theme_build_registry, which calls _theme_process_registry on each module hook_theme implementation.
    it also calls hook_theme on each engine and them implementation.
  • _theme_build_registry then allows you to hook into it and alter the cache built by invoking theme_registry in your module.

So what we need to do to get drupal to do an automatic lookup of our files is simply invoke those two functions on our modules theme path and then add them to the registry.


function uql_shortcode_theme_registry_alter(&$theme_registry) {
$templates = drupal_find_theme_functions($theme_registry);

/* PATH is important its the path to your module dir with the templates: */
$templates += drupal_find_theme_templates($theme_registry, '.tpl.php', PATH);

// Grab only the "extra" ones we have found and add them to the registry
$theme_registry += array_diff_key($templates,$theme_registry);
}

Leave a comment