Drupal 8 - Override the rendering of node page using hook

By xngo on March 17, 2019

Overview

In Drupal 8, you can override the rendering of the node page using hook. Hooks are functions that will be called at a specific time. What you have to do is to find the hook function that you want and then re-implement it to the your liking.

Drupal provides a lot of hooks so that you alter or extend the core behaviour. All available hooks can be found at https://api.drupal.org/api/drupal/core%21core.api.php/group/hooks/8.7.x.

In this tutorial, I want to override the node page of the content type Article. For this purpose, I will re-implement the hook_ENTITY_TYPE_view.

For your own hook function to be executed, it has to follow the following naming convention:

  • Change hook to your module name.
  • For our case, change ENTITTY_TYPE to node.

Implement your own hook in *.module file

Here is how I re-implement the hook_ENTITY_TYPE_view in my modules/tradesteps/tradesteps.module:

// Implement hook_ENTITY_TYPE_view
function tradesteps_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, 
        \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) 
{
    $bundle = $entity->bundle();
    if($bundle=='article')
    {
        // Access field data.
        $body = $entity->get('body')->getString();
 
        // Add more markup/html.
        $someText="bla bla bla bla bla bla ";
        $build['tradesteps_markup'] = array(
                '#markup' => $someText,
                '#prefix' => '<div class="addition-text-markup">Top Wrapper Markup...',
                '#suffix' => '</div>'
            );
        $build['tradesteps_container'] = array(
                '#type' => 'container',
                '#prefix' => '<div class="addition-text-container">Top Wrapper Container...',
                '#suffix' => '</div>'
            );
    }
 
}

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.