How to call a function in a Twig file
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.
2 Answers 2
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 .
In this example, we will build an extension to display a Drupal block directly in a Twig template:
src/MyTwigExtension.php
* 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' =>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()->getViewBuilder('block')->view($block); > >
src/MyTwigModule.services.yml
services: MyTwigModule.twig.MyTwigExtension: class: Drupal\MyTwigModule\MyTwigExtension tags: -