Skip to content

Latest commit

 

History

History
85 lines (66 loc) · 3.08 KB

3.4-twig-templates.md

File metadata and controls

85 lines (66 loc) · 3.08 KB

Overriding Twig Templates

From Working With Twig Templates:

Drupal allows you to override all of the templates that are used to produce HTML markup so that you can fully control the markup that is being output within a custom theme. There are templates for each page element ranging from the high level HTML to small fields.

Twig Debug Mode

To enable Twig Debug Mode:

  • If sites/default/services.yml exists proceed to next step. Otherwise copy sites/default/default.services.yml to sites/default/services.yml.
  • Edit sites/default/services.yml.
  • Under twig.config section, set debug: true.
  • Clear cache either by clicking Clear all caches on /admin/config/development/performance or running drush cr on the command line.

Once enabled you can use dump() to output all available variables or output contents of a particular variables:

All variables:
{{ dump() }}

Contents of `foo`:
{{ dump(foo) }}

Theme Hook Suggestions

When Twig debug mode is enabled, Drupal will suggest a few possible ways to override the markup and preprocessor for particular content blocks. This will be shown in the page HTML as comments.

For example:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'block' -->
<!-- FILE NAME SUGGESTIONS:
   * block--substable-content.html.twig
   * block--system-main-block.html.twig
   * block--system.html.twig
   x block.html.twig
-->

If you wish you make your own recommendations, you hook into the preprocessor for this particular element and make your own additional suggestions.

<?php
/**
* Implements hook_theme_suggestions_block_alter() for block templates.
*/
function substable_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  $suggestions[] = 'block__substable';
  $suggestions[] = 'block__substable__' . $variables['elements']['#id'];
}
?>

If you clear your cache and look again at the comments you should see the new suggestion in the list.

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'block' -->
<!-- FILE NAME SUGGESTIONS:
   * block--substable--substable-content.html.twig
   * block--substable.html.twig
   * block--substable-content.html.twig
   * block--system-main-block.html.twig
   * block--system.html.twig
   x block.html.twig
-->

Now you can create templates/block--substable.html.twig or block--substable--substable-content.html.twig, to override core block behavior.

The earlier a file name is in the file name suggestions above, the higher priority it will have. So by pushing to the end of the suggestions array, we are setting our template suggestions to have the highest possible priority.

Make sure you clear your cache after creating any new template files.

Additional Resources