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.
So how are we suppose to change some smaller details on page/content, fine tune it etc?
Where do I need to put these hooks. e.g. where would I put hook_page_top()?
Many thanks for your patience and time! I've been using Drupal only a few days. Learning curve isn't that bad, and it's been really enjoyable!
Hooks should go into the .module file of your module, and the "hook" part should be replaced with the name of your module E.g., if you module is called mymodule, it should be mymodule_page_top.
Actually in theming proper, you would add the alter functions in the theme itself. In Drupal 7 that would have been in template.php but in Drupal 8 you use MYTHEME.theme in exactly the same way.
Add new comment