2

I have a field field_a that has a template suggestion of field--node--field_a.html.twig. Using that field template suggestion, I've modified the field to render a certain way within the template field--node--field_a.html.twig.

If I then create a teaser view mode and want to have the field render slightly different within the teaser, how do I write the field template suggestion to target only the teaser view mode?

2

You can do it like so in your themes MYTHEME.theme file:

/**
 * Implements hook_theme_suggestions_field_alter().
 */
function MYTHEME_theme_suggestions_field_alter(&$suggestions, array $variables) {
  $element = $variables['element'];
  $suggestions[] = 'field__' . $element['#entity_type'] . '__' . 
  $element['#field_name'] . '__' . $element['#bundle'] . '__' . 
  $element['#view_mode'];
}

You can remove $element['#bundle'] but I left that in there, it will create new template suggestions so you can target view modes by node type instead of apply it to every teaser view mode of every node type.

You could just create two suggestions as well if you want:

/**
 * Implements hook_theme_suggestions_field_alter().
 */
function MYTHEME_theme_suggestions_field_alter(&$suggestions, array $variables) {
  $element = $variables['element'];

  $suggestions[] = 'field__' . $element['#entity_type'] . '__' . 
  $element['#field_name'] . '__' . $element['#bundle'] . '__' . 
  $element['#view_mode'];

  $suggestions[] = 'field__' . $element['#entity_type'] . '__' . 
  $element['#field_name'] . '__' . $element['#view_mode'];
}

This will create new suggestions, as:

field--ENTITY--FIELD-NAME--ENTITY-BUNDLE--VIEW-MODE.html and field--ENTITY--FIELD-NAME--VIEW-MODE.html.twig, so you would have:

field--node--field-a--article--teaser.html.twig and field--node--field-a--teaser.html.twig to use.

Then, of course, the normal code in the field template works just the same:

{% for item in items %}
  {{ item.content }}
{% endfor %}

Now you can markup fields for view modes of all node types, or also override it for each node type.

  • This is spot on, @Kevin! Thank you. Why do you think this is not part of standard template suggestions? – erier Jan 4 at 18:13
  • Not sure. I think there is a contrib module out there providing it. – Kevin Jan 4 at 18:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.