Twig Templates Overriding in Drupal 8
Posted By : Vishal Yadav | 17-Jul-2019
You can override Drupal templates by adding templates to your theme folder.
To override templates you need to:
- Locate the template you want to override.
- Copy the template file from its core location into your theme folder.
- Rename the template according to the naming conventions in order to target a more specific subset of areas where the template is used.
- Modify the template according to your wish.
You need to clear the cache once you copy a template file into your theme, Drupal will start using your instance of the template file instead of the core version.
Theme hook suggestions
Theme hook suggestions allows to overrides the template files with a specific naming convention.You can add or modify suggestions using the hooks:
- hook_theme_suggestions_HOOK(array $variables)
- hook_theme_suggestions_alter(array &$suggestions, array $variables, $hook)
- hook_theme_suggestions_HOOK_alter(array &$suggestions, array $variables)
When working with theme suggestion, Drupal can use its cache rather than the new templates as suggested. So Clear the cache if you experience this problem.
Twig Template naming conventions
Drupal follows a naming convention to load the templates. This allows you to override the templates by adding them to your theme or giving them a proper name.
These templates provide markup for the basic structure of the HTML-page
Base template name: html.html.twig
Examples override the base/html template:
The suggestions are numerous. The front page takes prediction and based on the internal path of the current page. You may change the front page through admin as "Administration > Configuration > System > Site information."
Base template: page.html.twig
Base template: region.html.twig
The region template is used when a page region finds some content. Custom region names are determined by the theme's .info.yml file.
Base template: block.html.twig
For example, a custom module called "custom" and a delta of "cus-block", the theme hook suggestion would be called "block--custom--cus-block.html.twig."
Base template: node.html.twig
Theme hook suggestions are made based on some factors, listed from the most specific template to the least. Drupal will use the most specific template first:
Note: Underscores (_) in a content type's machine name are replaced by hyphens (-).