Replace template using custom module in Drupal 8

Posted on: Tue, 11/05/2019 - 21:19 By: Arun AK

Sometimes you may need to alter a template that is provided by a module. Usually, you will be able to override the template by copy it into your themes template directory.

But in a case such as Drupal multi-site setup with a single code base and shared the theme, it is difficult to alter template specifically for a particular website. Then if you are doing it using a module you will be able to achieve for a particular website.

The hook hook_theme_registry_alter() will help to alter the template path for a particular theme function.

Then add this hook in your .module file:

function mymodule_theme_registry_alter(&$theme_registry) {
    $theme_registry['mycustomblock']['path'] = drupal_get_path('module', 'mymodule') . '/templates';

Where 'mycustomblock' is the theme function that used to render the template. You will be able to identify it once you enable the debug mode in Drupal.