twig - pass function into template

后端 未结 5 1032
清歌不尽
清歌不尽 2021-02-05 05:31

Currently I place my function in a class and pass an instance of this class into template and call my required function as a class method.

{{ unneededclass.blah(         


        
5条回答
  •  [愿得一人]
    2021-02-05 05:52

    I was as lost as you were, my friend, but after searching the web for an answer and found none, I decided to see if I could do it myself. Therefore, I wanted to post my solution here (even though I know this post is old), because this is the first hit on google if you search for this problem.

    Here it go, it is quite simple actually:

    I made a class which contains my functions and variables, for example:

    class functionContainer{
            function getRandomNumber()
            {
                    return rand();
            }
    }
    $values = array(
    'functions'=> new functionContainer()
    );
    

    So now we have $values as an array, which contains this object with a function "getRandomNumber()".

    When rendering the template file, include this class as a value:

    $twig->render('random.html', $values);
    

    This way, inside the template file, you can just call this method to call the function and get your result:

    {{ functions.getRandomNumber }}
    

提交回复
热议问题