How to call a function in a Twig file Let's say I create a function in a module file:

function _get_test() {
  return 'test';
}


How can I call this in any Twig file? For example *.html.twig, page.html.twig, node.html.twig etc. 

OR 

How can I pass a variable from PHP to Twig and display in any Twig file. 
For example *.html.twig, page.html.twig, node.html.twig etc.
You can define your own custom Twig functions in a custom module (but not in a theme). To find an example for how to do this, see this example in core/modules/system/tests/modules/twig_extension_test/src/TwigExtension/TestExtension.php.



Also see this blog post: Create Twig extensions for Drupal 8.


  In this example, we will build an extension to display a Drupal block
  directly in a Twig template:

{{ display_block('my_block_id') }}

  
  src/MyTwigExtension.php

&lt;?php

namespace Drupal\MyTwigModule;

/**
 * Class DefaultService.
 *
 * @package Drupal\MyTwigModule
 */
class MyTwigExtension extends \Twig_Extension {

  /**
   * {@inheritdoc}
   * This function must return the name of the extension. It must be unique.
   */
  public function getName() {
    return 'block_display';
  }

  /**
   * In this function we can declare the extension function
   */
  public function getFunctions() {
    return array(
      new \Twig_SimpleFunction('display_block', 
        array($this, 'display_block'),
        array('is_safe' =&gt; array('html')
      )),
  }

  /**
   * The php function to load a given block
   */
  public function display_block($block_id) {
    $block = \Drupal\block\Entity\Block::load($block_id);
    return \Drupal::entityManager()-&gt;getViewBuilder('block')-&gt;view($block);
  }

}

  
  src/MyTwigModule.services.yml

services:
  MyTwigModule.twig.MyTwigExtension:
    class: Drupal\MyTwigModule\MyTwigExtension
    tags:
      - { name: twig.extension }