Light-weight solution to provide custom view modes and suggest related templates in Drupal 7

When it comes to providing custom view modes for entities in Drupal, most developers turn immediately to Display Suite or Entity View Modes. Display Suite is very powerful, but I've found it to be far too "heavy" for most of my use cases. In this case, by "heavy" I mean that the module does way more than I need it to. It does a lot of things I simply don't want on my site. Entity view modes is a lighter-weight approach to supplying additional view modes, but I found that even it was cumbersome when it came to managing my view mode configuration in an easily-deployable way.

I wanted a simpler solution, and I knew it couldn't be that hard to provide this functionality in a custom, streamlined module.

The code snippets below do the following:

  • Define new display modes. As you'll see, this is super easy to do in code.
  • Suggest node templates based on the view mode of the given node. e.g. a teaser template vs. a full display template.
  • Suggest page templates based on the node type being viewed. e.g. alter the page markup for Article nodes.
/**
* Implements hook_entity_info_alter().
*
* Provide front-page feature and sub-feature view modes. Template suggestions
* are provided in example_preprocess_node().
*/
function example_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes']['front_feature'] = array(
    'label' => t('Front page feature'),
    'custom settings' => TRUE,
  );
  $entity_info['node']['view modes']['front_sub_feature'] = array(
    'label' => t('Front page sub-feature'),
    'custom settings' => TRUE,
  );
}

/**
* Implements hook_preprocess_node().
*/
function example_preprocess_node(&$variables) {
  // Provide template suggestions based on the view mode.
  // Example 1: node__front_feature
  // Example 2: node__article__front_feature
  if (!empty($variables['view_mode'])) {
    $variables['theme_hook_suggestions'][] = 'node__' . $variables['view_mode'];
    $variables['theme_hook_suggestions'][] = 'node__' . $variables['type'] . '__' . $variables['view_mode'];
  }
}

/**
* Implements hook_preprocess_page().
*/
function example_preprocess_page(&$variables) {
  // Provide template suggestions based on the node type.
  // Example 1: page__node__article
  if (!empty($variables['node']->type)) {
    $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->type;
  }
}

My two cents: In Drupal development, we all-to-often turn immediately to heavy-weight, all-encompassing solutions for extremely simple problems. Simple solutions that leverage Drupal core's great APIs are generally completely sufficient.

Related reading: Looks like I'm not alone in seeking a lean approach to D7 view modes and template suggestions. Check out this post by Brad Czerniak titled Lean Drupal with Content View Modes and Views.

Tags: