How to call a function in a Twig file

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
1
down vote

favorite
1












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.










share|improve this question





























    up vote
    1
    down vote

    favorite
    1












    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.










    share|improve this question

























      up vote
      1
      down vote

      favorite
      1









      up vote
      1
      down vote

      favorite
      1






      1





      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.










      share|improve this question















      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.







      8 theming






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 12 mins ago

























      asked 48 mins ago









      Rituraj Kumar

      8412




      8412




















          2 Answers
          2






          active

          oldest

          votes

















          up vote
          1
          down vote













          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 (click "View source").




          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



          <?php

          namespace DrupalMyTwigModule;

          /**
          * Class DefaultService.
          *
          * @package DrupalMyTwigModule
          */
          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' => array('html')
          )),


          /**
          * The php function to load a given block
          */
          public function display_block($block_id)
          $block = DrupalblockEntityBlock::load($block_id);
          return Drupal::entityManager()->getViewBuilder('block')->view($block);





          src/MyTwigModule.services.yml



          services:
          MyTwigModule.twig.MyTwigExtension:
          class: DrupalMyTwigModuleMyTwigExtension
          tags:
          - name: twig.extension






          share|improve this answer



























            up vote
            1
            down vote













            You do not call PHP functions in Twig. You can either create a custom Twig extension (see answer from leymannx) or use the global preprocess



            function MYTHEME_preprocess(array &$variables, $hook) 
            //this is a global hook, its variables are available in any template file
            $variables['foo'] = 'bar';



            foo will then render bar, but this global preprocess might run into caching problems though






            share|improve this answer




















            • It should better be hook_preprocess_HOOK to target a specific template.
              – leymannx
              31 mins ago







            • 1




              @leymannx I'm explicitly using the one without _HOOK suffix as global preprocess, the ones with a specfic _HOOK suffix aren't global
              – Hudri
              28 mins ago











            Your Answer







            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "220"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            convertImagesToLinks: false,
            noModals: false,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













             

            draft saved


            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdrupal.stackexchange.com%2fquestions%2f271770%2fhow-to-call-a-function-in-a-twig-file%23new-answer', 'question_page');

            );

            Post as a guest






























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            1
            down vote













            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 (click "View source").




            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



            <?php

            namespace DrupalMyTwigModule;

            /**
            * Class DefaultService.
            *
            * @package DrupalMyTwigModule
            */
            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' => array('html')
            )),


            /**
            * The php function to load a given block
            */
            public function display_block($block_id)
            $block = DrupalblockEntityBlock::load($block_id);
            return Drupal::entityManager()->getViewBuilder('block')->view($block);





            src/MyTwigModule.services.yml



            services:
            MyTwigModule.twig.MyTwigExtension:
            class: DrupalMyTwigModuleMyTwigExtension
            tags:
            - name: twig.extension






            share|improve this answer
























              up vote
              1
              down vote













              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 (click "View source").




              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



              <?php

              namespace DrupalMyTwigModule;

              /**
              * Class DefaultService.
              *
              * @package DrupalMyTwigModule
              */
              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' => array('html')
              )),


              /**
              * The php function to load a given block
              */
              public function display_block($block_id)
              $block = DrupalblockEntityBlock::load($block_id);
              return Drupal::entityManager()->getViewBuilder('block')->view($block);





              src/MyTwigModule.services.yml



              services:
              MyTwigModule.twig.MyTwigExtension:
              class: DrupalMyTwigModuleMyTwigExtension
              tags:
              - name: twig.extension






              share|improve this answer






















                up vote
                1
                down vote










                up vote
                1
                down vote









                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 (click "View source").




                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



                <?php

                namespace DrupalMyTwigModule;

                /**
                * Class DefaultService.
                *
                * @package DrupalMyTwigModule
                */
                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' => array('html')
                )),


                /**
                * The php function to load a given block
                */
                public function display_block($block_id)
                $block = DrupalblockEntityBlock::load($block_id);
                return Drupal::entityManager()->getViewBuilder('block')->view($block);





                src/MyTwigModule.services.yml



                services:
                MyTwigModule.twig.MyTwigExtension:
                class: DrupalMyTwigModuleMyTwigExtension
                tags:
                - name: twig.extension






                share|improve this answer












                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 (click "View source").




                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



                <?php

                namespace DrupalMyTwigModule;

                /**
                * Class DefaultService.
                *
                * @package DrupalMyTwigModule
                */
                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' => array('html')
                )),


                /**
                * The php function to load a given block
                */
                public function display_block($block_id)
                $block = DrupalblockEntityBlock::load($block_id);
                return Drupal::entityManager()->getViewBuilder('block')->view($block);





                src/MyTwigModule.services.yml



                services:
                MyTwigModule.twig.MyTwigExtension:
                class: DrupalMyTwigModuleMyTwigExtension
                tags:
                - name: twig.extension







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 36 mins ago









                leymannx

                6,04242356




                6,04242356






















                    up vote
                    1
                    down vote













                    You do not call PHP functions in Twig. You can either create a custom Twig extension (see answer from leymannx) or use the global preprocess



                    function MYTHEME_preprocess(array &$variables, $hook) 
                    //this is a global hook, its variables are available in any template file
                    $variables['foo'] = 'bar';



                    foo will then render bar, but this global preprocess might run into caching problems though






                    share|improve this answer




















                    • It should better be hook_preprocess_HOOK to target a specific template.
                      – leymannx
                      31 mins ago







                    • 1




                      @leymannx I'm explicitly using the one without _HOOK suffix as global preprocess, the ones with a specfic _HOOK suffix aren't global
                      – Hudri
                      28 mins ago















                    up vote
                    1
                    down vote













                    You do not call PHP functions in Twig. You can either create a custom Twig extension (see answer from leymannx) or use the global preprocess



                    function MYTHEME_preprocess(array &$variables, $hook) 
                    //this is a global hook, its variables are available in any template file
                    $variables['foo'] = 'bar';



                    foo will then render bar, but this global preprocess might run into caching problems though






                    share|improve this answer




















                    • It should better be hook_preprocess_HOOK to target a specific template.
                      – leymannx
                      31 mins ago







                    • 1




                      @leymannx I'm explicitly using the one without _HOOK suffix as global preprocess, the ones with a specfic _HOOK suffix aren't global
                      – Hudri
                      28 mins ago













                    up vote
                    1
                    down vote










                    up vote
                    1
                    down vote









                    You do not call PHP functions in Twig. You can either create a custom Twig extension (see answer from leymannx) or use the global preprocess



                    function MYTHEME_preprocess(array &$variables, $hook) 
                    //this is a global hook, its variables are available in any template file
                    $variables['foo'] = 'bar';



                    foo will then render bar, but this global preprocess might run into caching problems though






                    share|improve this answer












                    You do not call PHP functions in Twig. You can either create a custom Twig extension (see answer from leymannx) or use the global preprocess



                    function MYTHEME_preprocess(array &$variables, $hook) 
                    //this is a global hook, its variables are available in any template file
                    $variables['foo'] = 'bar';



                    foo will then render bar, but this global preprocess might run into caching problems though







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered 32 mins ago









                    Hudri

                    968218




                    968218











                    • It should better be hook_preprocess_HOOK to target a specific template.
                      – leymannx
                      31 mins ago







                    • 1




                      @leymannx I'm explicitly using the one without _HOOK suffix as global preprocess, the ones with a specfic _HOOK suffix aren't global
                      – Hudri
                      28 mins ago

















                    • It should better be hook_preprocess_HOOK to target a specific template.
                      – leymannx
                      31 mins ago







                    • 1




                      @leymannx I'm explicitly using the one without _HOOK suffix as global preprocess, the ones with a specfic _HOOK suffix aren't global
                      – Hudri
                      28 mins ago
















                    It should better be hook_preprocess_HOOK to target a specific template.
                    – leymannx
                    31 mins ago





                    It should better be hook_preprocess_HOOK to target a specific template.
                    – leymannx
                    31 mins ago





                    1




                    1




                    @leymannx I'm explicitly using the one without _HOOK suffix as global preprocess, the ones with a specfic _HOOK suffix aren't global
                    – Hudri
                    28 mins ago





                    @leymannx I'm explicitly using the one without _HOOK suffix as global preprocess, the ones with a specfic _HOOK suffix aren't global
                    – Hudri
                    28 mins ago


















                     

                    draft saved


                    draft discarded















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdrupal.stackexchange.com%2fquestions%2f271770%2fhow-to-call-a-function-in-a-twig-file%23new-answer', 'question_page');

                    );

                    Post as a guest













































































                    Comments

                    Popular posts from this blog

                    What does second last employer means? [closed]

                    List of Gilmore Girls characters

                    Confectionery