Changing Twig template of form items through the theme I have a block, which renders out a form using code that looks like this:

{{ attribute(form.facets, 'filter_' ~ filter.name) }}


I'd like to amend the markup and CSS classes for the various elements that are output, including fieldset, input, label etc. I appreciate that I can override the template files for fieldset for example, by creating a fieldset.html.twig file in my theme, but I don't want to change the markup for every fieldset element. I only want to apply my custom templates to form elements which are rendered out from a specific block.

I know that I can use a 'suggestion' (mytheme_theme_suggestions_alter) to alter the template for any element, but I can't see a way of determining if an 'input' for example, is an input within my block, or some other block on the site. Does anyone know how I'd identify this?
You can use drupal_static() together with the following two hooks in your module or your theme to add template suggestions for input elements based on the block ID where the input element is used in (same would work with fieldsets or any other form/render element):

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_block(&amp;$variables) {

  $bid = &amp;drupal_static('block_id', TRUE);
  $bid = $variables['elements']['#id'];
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME/MYMODULE_theme_suggestions_input_alter(array &amp;$suggestions, array $variables) {

  $bid = &amp;drupal_static('block_id', FALSE);

  if ($bid) {
    $suggestions[] = 'input__block__' . $bid;
    $suggestions[] = $variables['theme_hook_original'] . '__block__' . $bid;
  };
}


For example the search form textfield:

&lt;!-- FILE NAME SUGGESTIONS:
   * input--search.html.twig
   * input--search--block--neato-search.html.twig
   * input--block--neato-search.html.twig
   x input.html.twig
--&gt;


For example the password textfield:

&lt;!-- FILE NAME SUGGESTIONS:
   * input--password.html.twig
   * input--password--block--userlogin.html.twig
   * input--block--userlogin.html.twig
   x input.html.twig
--&gt;