Field template suggestions

04/07/2018


Having trouble getting HOOK_theme_suggestions_field_alter to do what I expect. Think I’m missing something key about naming precendence.

Tiny bit of context: I have several field–xyz.html.twig files in my theme that do nothing but remove the wrapping <div>s found in my default field template. Trying to create a preprocess function where I can point several fields at the same wrapper-less twig template. Because, cleaner.

Here’s what I’ve tried. Open to other methods!

I created mytheme/templates/field/no-wrapper.html.twig

I added this function to the mytheme.theme file.

function mytheme_theme_suggestions_field_alter(array &$suggestions, array $variables) {
  if (in_array('field__my_field', $suggestions)) {
    array_splice($suggestions, 0, count($suggestions), 'no_wrapper');
    kint($suggestions);
  }
}

The result of that kint() call is as expected:

array(1)
  string(10) "no_wrapper"

That is, no_wrapper is the only suggestion in the array. But it still uses field.html.twig. From the source:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'field' -->
<!-- FILE NAME SUGGESTIONS:
   * no-wrapper.html.twig
   x field.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/custom/my_theme/templates/fields/field.html.twig' -->

For what it’s worth, the field in question is a Field Collection field.

What gives?

I’ve also (somewhat blindly) tried:

function mytheme_preprocess_field__my_field(&$variables) {
  $variables['theme_hook_original'] = 'no_wrapper';
}

Which puts no-wrapper.html.twig at the top of the suggestions list, adds no_wrapper as the THEME HOOK but still renders field.html.twig.

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'no_wrapper' -->
<!-- FILE NAME SUGGESTIONS:
   * field--node--my-field.html.twig
   * field--node--my-node-type.html.twig
   * field--my-field.html.twig
   * field--field-collection.html.twig
   * no-wrapper.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/custom/my_theme/templates/fields/field.html.twig' -->

قالب وردپرس