Automatic Theme Registry Entries

In a previous post I covered how the template_files key in preprocess functions has been replaced by theme_hook_suggestions. A key thing to know is that Drupal will automatically create the necessary theme registry entries based on templates it finds in the current theme.

For example, the node module makes the theme hook suggestions of node__TYPE and node__ID but inspecting node_theme shows that there is no explicit declaration of theme registry entries to match these suggestions.

Chris Johnson, VP of Engineering
#Drupal | Posted

In a previous post I covered how the template_files key in preprocess functions has been replaced by theme_hook_suggestions. A key thing to know is that Drupal will automatically create the necessary theme registry entries based on templates it finds in the current theme.

For example, the node module makes the theme hook suggestions of node__TYPE and node__ID but inspecting node_theme shows that there is no explicit declaration of theme registry entries to match these suggestions. The manual theme registry entry declarations are not needed because Drupal automatically creates these entries while creating the theme registry through calls to drupal_find_theme_templates and drupal_find_theme_functions.

For example, if a file name node—story.tpl.php is found in your theme then the theme entry node__story will automatically be created due to a match of the beginning of the template name against node--. Node-- was used as the test from the base node theme entry along with a separator of --, which is the default if the theme entry doesn’t declare a pattern.

The drupal_find_theme_templates function can also be used if your module provides suggested templates as well as a shortcut to defining all of the theme entries. This can be a handy shortcut when your module can provide a lot of different suggestions along with default templates for the suggestions. The addressfield module uses this technique by calling drupal_find_theme_templates to augment the manually specified theme registry entries.

  1. function addressfield_theme() {
  2. $path = drupal_get_path('module', 'addressfield') . '/theme';
  3. $templates['addressfield_formatter'] = array(
  4. 'variables' => array('address' => <span class="caps">NULL</span>),
  5. 'template' => 'addressfield-formatter',
  6. 'path' => $path,
  7. );
  8. $templates += drupal_find_theme_templates($templates, '.tpl.php', $path);
  9. return $templates;
  10. }

Drupal also performs a similar search on function implementations via drupal_find_theme_functions. The comments in that function are informative for understanding both the template and function search mechanisms.

drupal_find_theme_functions
drupal_find_theme_templates

Chris Johnson

Chris Johnson

VP of Engineering