Drupal

Adding a Template in a Module rather than a Theme in Drupal 7

Generally speaking, a custom template goes into the theme’s folder. But what if you want to a custom template for a content type your module has created. By default, Drupal 7 will not search your modules directory. It turns out other people have already solved this for me and I found the answer here.

Add the following code into your mymodule.module file. Don’t forget to change the “mymodule” refererences.

/**
 * Implements hook_theme_registry_alter()
**/
function mymodule_theme_registry_alter(&$theme_registry) {
  $mod_path = drupal_get_path('module', 'mymodule');
  $theme_registry_copy = $theme_registry;       // munge on a copy
  _theme_process_registry($theme_registry_copy, 'phptemplate', 'theme_engine', 'pow', $mod_path);
  $theme_registry += array_diff_key($theme_registry_copy, $theme_registry);
  $hooks = array('node');
  foreach ($hooks as $h) {
    _mymodule_insert_after_first_element($theme_registry[$h]['theme paths'], $mod_path);
  }
}
/**
 * Helper function for re-ordering arrays (needed by theme_registry_alter)
*/
function _mymodule_insert_after_first_element(&$a, $element) {
  if(is_array($a)) {
    $first_element = array_shift($a);
    array_unshift($a, $first_element, $element);
  }
}

The second function is helper to manipulate the array.

Now you can create the theme override files in your modules/templates directory normally – for example page–article.tpl.php to override the appearance fo the “article” content type. As a start, just copy the node.tlp.php file from your base theme and modify it.

A simplified single function would look like this

function MYMODULE_theme_registry_alter(&$theme_registry) {
    $mod_path = drupal_get_path('module', 'MYMODULE');
    $theme_registry_copy = $theme_registry; // munge on a copy
    _theme_process_registry($theme_registry_copy, 'phptemplate', 'theme_engine', 'pow', $mod_path);
    $theme_registry += array_diff_key($theme_registry_copy, $theme_registry);
    $hooks = array('node');
    foreach ($hooks as $h) {
        if (is_array($theme_registry[$h]['theme paths'])) {
            $first_element = array_shift($theme_registry[$h]['theme paths']);
            array_unshift($theme_registry[$h]['theme paths'], $first_element, $mod_path);
        }
    }
}

Leave a Reply