I am trying to get the view mode of a node to use it in a field twig file by writing this function in my_theme, but it doesn't work:

function MY_THEME_preprocess_field(&$variables, $hook) {
 if ($node = \Drupal::routeMatch()->getParameter('node')) {
  $variables['view_mode_2'] = $node->view_mode;

I don't know if the variable is correct, but when I write some echo code I see that already the if condition isn't fulfilled.

EDIT: the if condition is only fulfilled when the node is open, but not when its teaser is shown as part of a view on the front page.

1 Answer 1


In a field template the view mode is stored here:


So you could check in preprocess, if the node is not displayed as teaser:

function MY_THEME_preprocess_field(&$variables) {
  if ($variables['element']['#view_mode'] != 'teaser')  {
    // node is not displayed on the front page

The same condition in a field twig:


{% if element['#view_mode'] != 'teaser' %}
  node is not displayed on the front page
{% endif %}
  • Ah, thank you, that's what I was searching! If anybody wants to know why this could be useful: My content type article has a text field for a subheadline. In order to wrap this headline with h-tags I created a custom field-xxx.html.twig file, but the problem is that the subheadline needs h3 tags in a teaser context, but h2 tags when showed as a full page. So the twig template is now checking the view mode and giving h2 or h3 tags depending on the view mode.
    – 0711master
    Jan 2, 2017 at 0:20
  • You can use the same condition in a field twig. I add this to the answer.
    – 4uk4
    Jan 2, 2017 at 7:19
  • So you don't need the preprocess anymore?
    – 0711master
    Jan 2, 2017 at 14:11
  • Yes, you've asked about preprocess, but for what you've described in the comment you don't need preprocess.
    – 4uk4
    Jan 2, 2017 at 14:18
  • Cool, good to know!
    – 0711master
    Jan 2, 2017 at 14:46

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.