Alter a View after the Render Process for Drupal 8, Drupal 9

Last updated March 19, 2021
Module Development8.9.x/9.1.x

Using hook_views_post_render() Drupal module developers can change the render array representation of a View before it gets displayed. You can use this to modify the computed HTML of a view just before it gets printed. This hook is similar to using a preprocess function for a template file, but in this case you have access to the whole render tree, not just the specific leaf covered by the template file you're preprocessing.

This hooks gets called after the Views object has been through the render process, and all the different configured displays and formatters have been applied, producing a render array representation of the results of the view. This hook receives an $output parameter which contains the render array, and only changes made directly to the $ouput variable will have any effect. This hook is the last chance to make changes to the render array before it is converted to markup.

You can use hook_views_post_render() to change #cache properties for the View, and to do things like add CSS classes to rows, and change the page title.

In this tutorial we'll:

  • Learn how to alter a view's rendered output right after the Views object completes the render phase of the build cycle.
  • Use hook_views_post_render() to change the title of the view's display

By the end of this tutorial you should know how to alter the render array generated by a View prior to it being passed to the theme layer and converted to HTML.