How to check for view mode in twig template? We have one field (field_tabs) that is used on Basic and Article content type. On the Basic page content type, it has a custom view mode (view_mode_vertical) and on the Article content type it has a different custom view mode (view_mode_horizontal).

Basic Page (default view mode) Manage Display


field_tabs (view mode = view_mode_vertical)
title
body


Article (default view Mode) Manage Display


field_tabs (view mode = view_mode_horizontal)
title
body


In a field.html.twig, how can we detect the view mode?

Our two options we explored was either a node template or field template (we went with field). We would like to do this in a way that we only need add the logic for detecting the view_mode in one place. In case we add a third or fourth view_mode, we can simply add another elseif (or switch case) to the code. 

Sample Twig code we were looking for:

{% if view_mode == 'view_mode_vertical' %}
  &lt;div class="tabs__vertical"&gt;...&lt;/div&gt;
{% else %}
  &lt;div class="tabs__horizontal"&gt;...&lt;/div&gt;
{% endif %}
In a field.html.twig, how can we detect the view mode?


In a field template there is no top level variable for the view mode like in the node template. You can create one and then your twig code should work:

{% set view_mode = element['#view_mode'] %}


Another option is to add a template name suggestion, see Field template for display mode.

Both are valid options. There are many projects heavily depending on Twig logic while other projects prefer PHP in preprocess and template name suggestion hooks.