Drupal Suggests Page template for Revisions nodes

leopathu on Wed, 01/27/2021 - 23:54
drupal revisions

Drupal has a lot of amazing functionalities within it. Revisions are one among them, actually, it helps us to manage the different versions of the node. Whenever we can get back our old version of the node. One more interesting thing is this there is a module diff as contrib module which will help us to view the difference between each version. It shows the difference in fields level so we can see the difference of each field's data in side by side.

We faced one of the issues in the revisions full node view page. Actually, we applied a separate page template for the article content type. But when we loaded the old version of the revision node. It won’t show as same as the default version. Problem is that the revisions page not taking the same page template as a default version.

But we did it with the small tweaks by altering the theme suggestions, the below code shows that how we made it possible,

/**
* Implements hook_theme_suggestions_HOOK_alter().
*/
function twist_theme_theme_suggestions_page_alter(array &$suggestions, array $variables) {
 $current_route = \Drupal::routeMatch()->getRouteName();
 // Apply same page template for revision nodes to get full functionality.
 if ($current_route == 'entity.node.revision') {
   $node = \Drupal::routeMatch()->getParameter('node');
   $revision = \Drupal::routeMatch()->getParameter('node_revision');
   $node = ($node instanceof \Drupal\node\NodeInterface) ? $node : \Drupal::entityTypeManager()->getStorage('node')->loadRevision($revision);;
   if ($node instanceof \Drupal\node\NodeInterface && !$node->isDefaultRevision()) {
     $content_type = $node->bundle();
     $suggestions[] = 'page__node__' . $content_type;
   }
 }
}

In the above code we check the current route it the node revision route then check the loaded entity is not the default revision if all the conditions are passed then we suggested the page__node__$content_type templates for the page. After that, the page will look the page--node--page.twig.html file.

Add new comment