Share icon

Render a Drupal node in drupal 8 twig template and module PHP code is a bit different from Drupal 7 because Drupal 8 uses Symfony and twig format, follow the step and you will available to render a node in Drupal 8 templates 

Step 1.

create hook_preprocess_page in your yourtheme.theme file 

and paste code (rename your theme name at the place of hook)

$nid = 130;
$entity_type = 'node';
$view_mode = 'teaser';

$values = \Drupal::entityQuery('node')->condition('nid', $nid)->execute();
$node_exists = !empty($values);

if($node_exists){
    $builder = \Drupal::entityTypeManager()->getViewBuilder($entity_type);

    $storage = \Drupal::entityTypeManager()->getStorage($entity_type);
    $node = $storage->load($nid);
    $build = $builder->view($node, $view_mode);
    $output = render($build);
}else{
    $output = "Given Node Not Exists";
}

$variables['node_130'] = $output; // you can use whatever name of variable as your wish in single word

 

Step 2

Now render the node where you want just using

{{node_130}}

 

It will render the node teaser mode to that template section because we mention the teaser mode at the beginning of code.

If you want to render node different you can create the view mode of drupal 8. We can create the different tutorial for that and just given machine name of the mode in place of teaser mode

 


Please Comment your thoughts and feedback below and add something if you found good in anywhere to help others

Hit a like Button If you like the Post.

Many Thanks

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.