1

Content type - article , view modes - teaser, vma, vmb. There are 3 views , 2 on the left sidebar called vma view mode and vmb view mode, the one on the right is called teaser view mode. All the views show unformatted list of content using view modes vma, vmb and teaser respectively. How to check for view mode in twig template? required

code i tried

  • Is this for debugging of Twig in general or do you have a follow up question for the linked topic? – 4k4 Sep 19 '18 at 16:07
1

Don't put too much logic into your templates. Simply add the field template suggestion by implementing hook_theme_suggestions_HOOK_alter to respect view modes from within your theme or custom module:

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

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

Now you can add templates following this pattern: field--node--field-myfield--article--teaser.html.twig.


When using Layout Builder or Display Suite you might need to check what else you find inside $variables['element'] by printing its values with Kint (sub-module of Devel) via ksm($variables['element']) and then build the template suggestion from what you find there.

protected by Community Sep 20 '18 at 6:59

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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