We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to handle closures in volt?

Please see the following code wrote in controller:

     $this->view->setVar("test", function($t){
        return "hello ".$t;
     });

In volt view file i tried: {{ test("Salsan") }} but it is not taking. It throws an error like: "Undefined function 'test' in C:\wamp\www\invo\public/../app/views/index/index.volt on line 25"

But its working fine on PHP code: <?php echo $test(); ?>

Please give me an advise on it.

edited Mar '14

If you want to add a new function, you can do it in your bootstrap file. Mine looks like this:

$DI->set('view',function() use($Config){
    $View = new \Phalcon\Mvc\View();
    $View->setViewsDir($Config->dirs->views);
    $View->registerEngines(['.phtml'=> function($View,$DI) use ($Config){

            $Volt = new \Phalcon\Mvc\View\Engine\Volt($View,$DI);
            $Volt->setOptions([ 'compiledPath'      =>  $Config->dirs->views_compile,
                'compileAlways'     =>  $Config->views_always_compile,
                'compiledSeparator' => '::'
            ]);
            $Compiler = $Volt->getCompiler();
            $Compiler->addFunction('strtotime','strtotime');
            $Compiler->addFunction('number_format','number_format');
            $Compiler->addFunction('trim','trim');
            $Compiler->addFilter('e_char',function($resolvedArgs,$exprArgs){
                    return 'htmlspecialchars('.$resolvedArgs.')';
            });
            return $Volt;
    }]);
    return $View;
});

I haven't tried it, but you may be able to use a closure as the second argument to addFunction() instead of a string.