Module Development

Alter a View before It's Rendered for Drupal 8, 9, and 10

Developers can implement hook_views_pre_render() to make changes to a ViewsExecutable object and affect the render array that gets generated by the render phase of a view. By the time hook_views_pre_render() gets invoked, the data to display has already been collected, and all things like field formatter configuration have been loaded. This hook gives you the opportunity to dynamically alter that configuration before it's passed to the code in the different field handlers that will ultimately calculate and return a render array by combining the field configuration with the query results.

You might, for example, dynamically change the label used in a table depending on context that doesn't exist in the view itself. Another example, and the one we'll use here, is transforming a view's rows into a slider (or tabs, or an accordion). That requires that you alter the views object before rendering and attach a custom JavaScript library. If the thing you want to change is the configuration of the display or any fields, or the contents of the results (versus the presentation of the results) of a view, than hook_views_pre_render() is the right place to do that. If you're looking to alter the generated render array than you'll likely want to use hook_views_post_render().

In this tutorial we'll:

  • Alter a ViewsExecutable object using hook_views_pre_render() before the view is rendered.
  • Attach custom JavaScript (or CSS) to a view.
  • Transform a view of article nodes into an interactive slider using the Slick Slider JavaScript library and some custom JavaScript code.

By the end of this tutorial, you should know how to alter the render array of a view and attach custom and third-party asset libraries in a Drupal site.