Override existing theme templates in a D8 module
My example will be overriding the page.html.twig
theme template
I wanted a different header when my custom module is active. My header code is in my theme’s page.html.twig
. I want to override that template in my own module.
There are two steps:
- Create the new template in your module
- Tell the module to override the same template in the theme with
hook_theme_registry_alter
in my.module
file.
Create new page.html.twig
template
Copy the existing page.html.twig
template from the theme into the /templates
folder in your module which we’ll call my_module
. Make the changes you need.
Override the theme’s template
Theme templates will take precedence over module templates. We have to use hook_theme_registery_alter
in the .module
file of our custom module.
In my_module/my_module.module
/**
* Implements hook_theme_registry_alter
*/
function my_module_theme_registry_alter(&$theme_registry) {
$theme = \Drupal::theme()->getActiveTheme()->getName();
if ($theme == 'my_theme') {
$theme_registry['page']['path'] = drupal_get_path('module', 'my_module') . '/templates';
}
}
Change the bolded my_module
and my_theme
with the machine names of your module and theme.
I want to make sure my module doesn’t override, say, the admin theme. So the if
wrapper checks for the right theme first.
If you put your template in a subfolder like /templates/subfolder
in the $theme_registry
line from '/templates'
to '/templates/subfolder
.