Drupal 8/9 - Add Twig template suggestions for Form Elements

Submitted by pierre on

You can add Twig Template Suggestions for Form Elements in drupal 8/9 using hook_theme_suggestions_input_alter():

/**
* @param array $suggestions
* @param array $variables
* @param $hook
*/

function yourtheme_theme_suggestions_form_element_alter(array &$suggestions, array $variables, $hook) {
  if (isset($variables['element']['#id'])) {
    $id = str_replace("-", "_", $variables['element']['#id']);
    $suggestions[] = 'yourtheme__' . $hook . '__' . $id;
  }
}

In page source you can see the result for the search block form element

<!-- THEME DEBUG --> 
<!-- THEME HOOK: 'form_element' --> 
<!-- FILE NAME SUGGESTIONS: 
  * yourtheme--form-element--edit-keys--2.html.twig 
  x form-element.html.twig --> 
<!-- BEGIN OUTPUT from 'core/themes/bartik/templates/form/form-element.html.twig' --> 

<div class="js-form-item form-item js-form-type-search form-type-search js-form-item-keys form-item-keys form-no-label">

Enjoy!

Categories