Show node data in system block template on Drupal 10

If we need to show data from field of node in block twig template, first of all we need to add some code in .theme file of our theme

function YOUR_THEME_NAME_preprocess_block(&$variables) {
 // Get the current node object.
 $route_match = \Drupal::routeMatch();
 $node = $route_match->getParameter('node');
 // Check if the current page is a node.
 if ($node instanceof \Drupal\node\NodeInterface) {
   // Pass the node object to the block template.
   $variables['content']['#node'] = $node;
 }
}

after that we need open block twig template, that we need, and put in this code

{% if content['#node'] is defined %}
 <div class="my-block">
   <h2>{{ content['#node'].getTitle }}</h2>
   <p>{{ content['#node'].field_machine_name.value }}</p>
 </div>
{% endif %}

Plain text

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