How to display node details and call function in *.html.twig I work in D8, I create a custom module first_module. By modules create a url and display all nodes by *.html.twig file.

Write code in controller.php

public function contentthree() {

  $connection = Database::getConnection();

  $query = $connection-&gt;select('node', 'n');
  $query-&gt;fields('n', ['nid', 'type']);

  $groups = $query-&gt;execute()-&gt;fetchAll();

  foreach ($groups as $group) {
    $events[] = [$group-&gt;nid, $group-&gt;type];
  }

  return [
    '#theme'  =&gt; 'first_module_display',
    '#events' =&gt; $events,
  ];
}


In *.module

function first_module_theme($existing, $type, $theme, $path) {

  return [
    'first_module_display' =&gt; [
      'variables' =&gt; ['events' =&gt; NULL],
      'template'  =&gt; 'first-module-list',
    ],
  ];
}

function _get_node_details() {

  $output = 'Welcome D8';

  $output .= 'Node Details';

  return $output;
}


and create templates first-module-list.html.twig and display data

{%for key, data in events %}

{%for key1, data1 in data %}

   {{ data1 }}

{% endfor %}

{% endfor %}


work fine and showing data correct. But, my question is how to call function _get_node_details() and how to render node details in first-module-list.html.twig files?
I think I would have implemented this feature differently. Let me just answer the specific question, and then I will tell you an alternative approach.

Custom 'functions' in Twig

The easiest thing for you could be to Implement a twig macro.

However, macros could be limiting. To have all the PHP power you can create a twig extension function

If you are in a rush and are into bad practices, then there is the twig tweak php filter, so that you can do this:

&lt;div class="bad-practice"&gt;
     {{ 'return _get_node_details();'|php }} 
&lt;/div&gt;


Alternative implementation using Drupal views


Create a Drupal View, with a Block Display.
Place the new Block, using the Block Layout.
If you need to do a heavy alteration use a hook_views_data_alter().