In Drupal 7, hook_page_alter was a convenient way to go when we needed to modify page elements that were added by other modules. Drupal 8 does away with this hook - hopefully for the better. To fill the void created by hook_page_alter’s dismissal, the following hooks have been introduced.
In addition, we can still implement hook_preprocess_page, which does let us override or add content to the page. However, this hook is intended to prepare variables for the template and isn’t supposed to make drastic changes to the content.
I have gathered a list of use cases that I often face when needing to adjust page elements. Let’s see what are some possible solutions for each.
Applying attributes to HTML elements
I often need to apply attributes - mainly CSS classes - dynamically to certain elements. This is a job for hook_preprocess_page. That hook can prepare and place the necessary HTML attributes into a variable, which in turn can be printed out at the appropriate place in the template file.
Adding elements to the page
Previously with hook_page_alter, we were able to stick new elements into any part of the page, be it the main page content or one of the regions. This is no longer possible in Drupal 8. However, hook_page_top and hook_page_bottom allows us to add our items to the top and bottom region of the page, respectively. These two behave similarly to an alter hook, meaning they receive an array argument where they can add their items, as opposed to returning them.
Changing the template file used
In Drupal 7, the preprocess function received a theme_hook_suggestions array. Modifying the values in that array allowed us to influence what template file was used for rendering. The counterpart to this functionality can be achieved with hook_theme_suggestions_HOOK in Drupal 8. This hook is supposed to return an array of new template suggestions, which normally extends the range of possible templates. Similarly hook_theme_suggestions_HOOK_alter can be used to remove the suggestions of other modules.