September 23, 2015 12:53 PM

Every Drupal CMS developer has run into Views module and its templates architecture to adapt the web to the client's design requirements.

Views

As we said before in the previous post, Views is the most used Drupal module and has Drupal 6 and Drupal 7 versions. It is a great tool which lets us perform hard querys to de database with its UI and set how data will be shown to the end users easily.

Views architecture

Views let display query data results in different ways: blocks, pages, RSS feeds RSS, etc, called Displays, even it is possible to configure different Styles for the output like lists, tables, charts, slideshosw, etc. All thanks to its powerfull API, which could be extended by other modules.

Views architecture has three levels:

  • Display
    Drupal Views displays
  • Style
    Drupal Views styles
  • Row style
    Drupal Views row styles

Views templates

This structure influences how Views generates HTML output, each level correspondes to a different template.

Drupal views templates

Views let any theme to overwrite every level: generic, by view, by style, by field, even by any possible combination of them, giving great flexibility to themers.

Views preprocess and process

There is another way to customize a view output in PHP. Views uses Drupal preprocess and process behaviours in template.php theme file.

Drupal 6 and Drupal 7 differences

Drupal 6 had a preprocess function for every possible template. It was required the existence of the template (tpl.php) for the function to be executed.

In Drupal 7 this has changed:

  • it is not required anymore the existence of the template in order to execute the preprocess function.
  • it is no possible to specifiy a preprocess/process function for each view, leaving us with just the generic preprocess functions:
    • mytheme_preprocess_views_view(&$vars) - generic for all views
    • mytheme_process_views_view(&$vars) - generic for all views
    • mytheme_preprocess_views_view_list(&$vars) - generic for List style views
    • mytheme_preprocess_views_view_field(&$vars) - generic for each field
    • etc.

There is an issue to let Drupal 7 and 8 themes implement a preprocess/process function per view as it is possible in Drupal 6, but it is in development (see issue).

Until it is fixed there is a way to achieve that behaviour:

<?php
/**
  * Generic preprocess that is still working on D7
  */
function MYTHEME_preprocess_views_view_fields(&$vars) {
  if (isset($vars['view']->name)) {
    $function = __FUNCTION__ . '__' . $vars['view']->name . '__' . $vars['view']->current_display;
   
    if (function_exists($function)) {
     $function($vars);
    }
  }
}

/**
  * Then the specific preprocess that worked without the above code for D6
  */
function MYTHEME_preprocess_views_view_fields__VIEWNAME__DISPLAY(&$vars) {
  // my specific preprocess code
}
?>