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.

2 thoughts on “How to create custom template suggestion for node render”

  1. Good day! Do you know if they make any plugins to help with Search Engine Optimization? I’m trying to get my blog to rank for some targeted
    keywords but I’m not seeing very good success. If you
    know of any please share. Thank you!

    1. Hi Twicsy,

      Yes, there are multiple SEO plugins are available for your WordPress blogging website. I preferred ALL in SEO, and RAnk Math because they work pretty well with all the rich snippets for SEO. Are you using WordPress or Drupal for your blogging website?

Leave a Comment