Skip to main content

Overriding a twig template in a custom module in drupal 8

Member for

2 years 2 months
Submitted by admin on

To override a twig template in a custom module the theme hook needs to see which template is needing going be altered and the parent module origin Twig file. In the .module of the custom module that is going to nullify the parent template add the code below.

 

The _theme hook example below is overriding the Blazy modules blazy.html.twig file. The second preprocessor function hook is adding a custom variable so it can be accessed by the twig template in your module.

/**
 * Implements hook_theme().
 */

function slider_overlay_text_theme($existing, $type, $theme, $path)
{
    $templates = $path . '/templates';

    $return['blazy'] = [
        'template' => 'blazy',
        'path' => $templates
    ];
    return $return;
}


/**
 * Prepares variables for blazy.html.twig templates.
 * Implements hook_preprocess_HOOK() for field templates.
 */
function slider_overlay_text_preprocess_blazy(&$variables)
{
    $variables['display_hero_text'] = 'right';
}