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' %}
  <div class="tabs__vertical">...</div>
{% else %}
  <div class="tabs__horizontal">...</div>
{% endif %}
  • IMO its easier to just make the view mode twig suggestions in that case. I don't like having one file with a ton of conditional logic in it for display.
    – Kevin
    Apr 25, 2018 at 20:02
  • @Kevin so something like node--basic--view-mode-vertical.html twig? Apr 25, 2018 at 20:21

1 Answer 1


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.

  • the field template for display mode did the job. Apr 25, 2018 at 20:29
  • Thanks! But I think it must be: elements['#view_mode']! Also interesting for this part is : {% for key, value in _context %} {{ key }} {% endfor %} to geht all given variables!
    – Bruno
    Oct 25, 2018 at 15:39
  • 1
    @Bruno, a field has usually element as render element. You are referring to a different template probably.
    – 4uk4
    Oct 25, 2018 at 15:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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