How to create custom template suggestion for node render

Drupal Twig Debug

Custom template suggestion makes the Drupal application UI in a better shape. So if you want you can customize how do you want to render your content. We have User, Node, and Taxonomy contents within our Drupal application, so which content you want to render with the custom templates that you can do. Here in this article, I take an example odd nodes will come with one custom template and even nodes will fall in another template.

How to render two different node templates to use in node rendering?

Here we are going to use “hook_theme_suggestions_HOOK_alter” function in our custom_theme.theme file. The logic is getting the node object from route information getting the node id only if node URL passed, so whether the nid is odd or even based on that we just defined the template as node__first or node__second. So within our theme folder inside the templates folder, we need to place the file as node–first.html.twig and node–second.html.twig. Basically, these file overrides the existing default template node.html.twig. So you need to take care of all the variables from parent templates to place the HTML based on the UI part.

/**
* Implements hook_theme_suggestions_HOOK_alter() for node templates.
*/
function hook_theme_suggestions_node_alter(array &$suggestions, array $variables) {
$node = \Drupal::routeMatch()->getParameter('node');
if(isset($node)){
$nid = $node->id();
if($nid % 2 == 0){
$suggestions[] = 'node__' . 'second';
}
else{
$suggestions[] = 'node__' . 'first';
}
}

I hope you are understanding this concept, if you have any queries or any feedback please use the below comment section. Thanks for reading till this point, will catch you in another topic.

Leave a Comment

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This