phpdrupaltwigdrupal-8drupal-9

Drupal 8/9 Override twig with custom module


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.


Solution

  • 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.