Drupal 8/9 Override twig with custom module

2k views Asked by At

I've tried everything I've found to modify a views_view_field, starting with the official docs. I've also tried multiple ways and parameters for the hooks HOOK_theme (with and without the parameters 'path', 'base hook') and HOOK_theme_registry_alter, but I'm still unable to make the twig in my module to override the original.

To make things simpler, I'm testing without any custom theme, without any folders under /templates, and the view I'm trying to modify is linked inside the admin pages. The twig suggestions clarify that the twig being displayed is the "stable" theme one.

2

There are 2 answers

0
bradtreloar On BEST ANSWER

The template in the theme takes precedence over the template in your module, so you will need to implement HOOK_theme_registry_alter to force Drupal to get the template from your module's folder.

/**
 * Implements hook_theme_registry_alter().
 */
function mymodule_theme_registry_alter(&$theme_registry) {
  // Replace the path to the registered template so that Drupal looks for
  // it in your module's templates folder.
  $theme_registry['views_view_field']['path'] = drupal_get_path('module', 'mymodule') . '/templates';
}

Make sure you clear your cache to force the theme registry to be updated.

0
Tinto On

For Drupal 9.3.0 and above: Drupal_get_path() and drupal_get_filename() have been deprecated in Drupal 9.3.0 and are removed completely in Drupal 10.0.0.

Here's a working example for newer versions:

/**
 * Implements hook_theme_registry_alter().
 */
function mycustommodule_theme_registry_alter(&$theme_registry) {
  // Override an existing Twig template file with the one provided by my custom module
  $theme_registry['views_view_field']['path'] = \Drupal::service('extension.list.module')->getPath('mycustommodule') . '/tpl';
}

Place your Twig template file in the template folder of your custom module (in this case: /mycustommodule/tpl).