In Drupal, custom template hooks provide a powerful mechanism for overriding default templates and creating more tailored layouts or presentations for specific content or contexts within your theme. Here's a breakdown of the concept:
Templates in Drupal are often defined using theme hooks, which are unique identifiers that map to template files. Core and contributed modules provide many default theme hooks for various elements like nodes, blocks, comments, etc. Custom template hooks allow you to extend this system by creating your own hooks and associating them with specific template files in your theme.
Define the Hook Function:
In your custom module's .module file, implement a function using the naming convention hook_theme_HOOK()
. Replace HOOK
with a unique identifier for your custom hook.
function my_custom_module_theme_my_custom_hook(array $variables) {
// Return the theme suggestions array
return [
'my_custom_theme_hook__suggestion1', // Suggestion 1 template name
'my_custom_theme_hook__suggestion2', // Suggestion 2 template name
];
}
Implement Template Logic:
These template files will contain the custom HTML or Twig code for your specific presentation. You can access variables passed from the context using Twig syntax.
Template Suggestion Selection:
Drupal's theme system uses a hierarchy to determine which template to use. The most specific suggestion matching the current context takes precedence.
/**
* Implements hook_theme().
*/
function MY_MODULE_theme($existing, $type, $theme, $path) {
return [
'commerce_order__admin' => [
'template' => 'commerce-order--admin-custom',
],
];
}
hook_theme_suggestions_HOOK_alter()
to modify the default suggestions provided by other modules for existing theme hooks.