0

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

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

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

1 Answer 1

1

First you define Filters in the getFunctions method, if these are Filters define them in the getFilters method.

Then the Twig_SimpleFilter and Twig_SimpleFunction object expects an array as the 2nd argument.

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'))
        );
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.