twig - pass function into template

后端 未结 5 1039
清歌不尽
清歌不尽 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 06:04

    Although you cannot PHP callable directly, twig is extensible. You can add a callable filter, so you can apply to PHP functions passed to template.

    namespace My\Twig\Extension;
    
    class LambdaFilter extends \Twig_Extension {
    
        public function getName() {
            return 'lambda_filter';
        }
    
        public function getFilters() {
            return array(
                new \Twig_SimpleFilter('call', array($this, 'doCall'))
            );
        }
    
        public function doCall() {
            $arguments = func_get_args();
            $callable = array_shift($arguments);
            if(!is_callable($callable)) {
                throw new InvalidArgumentException();
            }
            return call_user_func_array($callable, $arguments);
        }
    
    }
    

    Now if you pass variable my_func to template, you can do my_func|call(arg1, arg2). You can even do higher order functions "array_filter"|call(my_array, my_func) and you can always do more things in filter like accepting array as parameters and so on.

提交回复
热议问题