简体   繁体   English

PHP Twig扩展错误

[英]PHP Twig extension error

Im trying to create a twig extension 我正在尝试创建一个树枝扩展

$loader = new \Twig_Loader_Filesystem(__DIR__.'/../views');
$this->layout = new \Twig_Environment($loader, array(
  'cache' => '/../views/cache',
  'auto_reload' => true
));
$this->layout->addExtension(new \App\Lib\twig_microtime());

And App\\Lib\\twig_microtime 和App \\ Lib \\ twig_microtime

class Twig_microtime extends \Twig_Extension {

    private $start;

    public function getFunctions() {

        return array(

            'microtime_start' => new \Twig_SimpleFilter($this, 'microtimeStart'),
            'microtime_end'   => new \Twig_SimpleFilter($this, 'microtimeEnd')
        );
    }

    public function microtimeStart() {

        $this->start = microtime(true);
    }

    public function microtimeEnd() {

        return 'eeeee';
    }

    public function getName() {

        return 'microtime_extension';
    }
}

So at my layout Im trying to call {{ microtime_end() }} but im getting this error 因此,在我的布局中,我尝试调用{{microtime_end()}},但出现此错误

An exception has been thrown during the compilation of a template ("Argument 2 passed to Twig_NodeVisitor_SafeAnalysis::setSafe() must be of the type array, null given 模板的编译过程中引发了异常(传递给Twig_NodeVisitor_SafeAnalysis :: setSafe()的参数2必须为数组类型,给定为null

First you define Filters in the getFunctions method, if these are Filters define them in the getFilters method. 首先,您需要在getFunctions方法中定义过滤器,如果这些过滤器是在getFilters方法中定义它们。

Then the Twig_SimpleFilter and Twig_SimpleFunction object expects an array as the 2nd argument. 然后,Twig_SimpleFilter和Twig_SimpleFunction对象期望将数组作为第二个参数。

So try this: 所以试试这个:

public function getFilters() {

        return array(
             new \Twig_SimpleFilter('microtime_start', array($this, 'microtimeStart')),
             new \Twig_SimpleFilter('microtime_end', array($this, 'microtimeEnd'))
        );
}

But i guess you actually mean to create Functions. 但是我想您实际上是要创建功能。
This would be so: 情况如下:

public function getFunctions()
    {
        return array(
             new \Twig_SimpleFunction('microtime_start', array($this, 'microtimeStart')),
             new \Twig_SimpleFunction('microtime_end', array($this, 'microtimeEnd'))
        );
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM