Drupal 8/9 - Add Twig template suggestions for Container Element

Submitted by admin-matapedia on

You can add Twig Template Suggestions for Container in drupal 8/9 using hook_theme_suggestions_container_alter.

If you follow the Drupal rules about templating suggestions, you can propose several suggestions for each container element.

By default, the hook_template_preprocess_container propose no suggestions for container elements.
We can add special suggestions for normal container and forms containers with parents.

function yourtheme_theme_suggestions_container_alter(array &$suggestions, array $variables)
{
  $container = $variables['element'];

  // Add here the suggestions you want to propose for normal container and forms containers
 
  if (isset($container['#array_parents'])) {
    $suggestions[] = 'container__form';
  }
  else {
    $suggestions[] = 'container__simple';
  }

  if (isset($container['#type']) && $container['#type'] != 'container') {
    $suggestions[] = 'container__' . $element['#type'];
  }

  if (isset($container['#type']) && $container['#type'] == 'container' && isset($container['children']['#type'])) {
    $suggestions[] = 'container__' . $container['children']['#type'];
  }
}

In page source you can see the result for the container element (simple and form containers)

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'container' -->
<!-- FILE NAME SUGGESTIONS:
   * container--view.html.twig
   * container--simple.html.twig
   x container.html.twig
-->
<!-- BEGIN OUTPUT from 'core/modules/system/templates/container.html.twig' -->

or

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'container' -->
<!-- FILE NAME SUGGESTIONS:
   * container--actions.html.twig
   * container--form.html.twig
   x container.html.twig
-->
<!-- BEGIN OUTPUT from 'core/modules/system/templates/container.html.twig' -->

Enjoy!

Tags
Categories