Get node's view mode within template_preprocess_page

by usernameabc   Last Updated March 14, 2019 21:07 PM

We have to get the current node's view_mode from within the mymodule_preprocess_page(&$variables) hook. When we tried the following we could not get the view_mode after performing some validation to make sure we have a node object.

How can we get the current node's view_mode from within the template_preprocess_page(&$variables) hook?

Here is what we tried to do

function mymodule_preprocess_page(&$variables) {
  $node = $variables['node'];
  if(isset($node) && is_object($node) {
    // Tried printing variables but cannot find `view_mode`
    ksm($node);
  }
}
Tags : 8 nodes hooks


Answers 1


I needed to put a class based on view mode onto my pages. I seem to remember that view mode is handled separately from the node data. My solution was actually based on using the Display Suite submodule Switch View Mode (was already using DS). This module creates a new base field in the entity and sets the view mode to it.

This let me use the following code to create the class:

$view_mode = $node->ds_switch->value;
if (!empty($view_mode)) {
   $variables['page_class'] .= " node-view-{$view_mode}";
}

This solution won't work with out the module. A bit of tracing on how this works shows that it is based on using hook_entity_view_mode_alter() to get the view mode and add it to the ds_switch field on the node.

This field seems to be added by using the hook_entity_base_field_info(). See the ds_switch_view_mode.module file in the Display Suite code for details on this.

CG Monroe
CG Monroe
March 14, 2019 20:49 PM

Related Questions


Update a field on a node after hitting save

Updated April 10, 2015 21:31 PM

hook_load vs. hook_node_load?

Updated April 22, 2016 08:03 AM

Change / Increase the node title length

Updated July 15, 2015 13:03 PM

Getting a list of altered fields when saving a node

Updated August 24, 2015 18:03 PM

hook_node_access called more than once

Updated February 16, 2016 02:03 AM