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

Access custom service from Volt

I know that you can access a service of the DI from volt just by using its name.

My question is: if I have a custom service, that receive a parameter, is it possible to reach it directly from volt in some way? Because i know that you can write:

$this->view->setVar('name', $this->getDI()->get('customService', array($parameter)));

But I'd like to skip that line

edited Jan '16

Hi, If your service is set in di, you can simply acess it like:

{{ customService(parameter) }}

you don't need to assign it to view, however note that you still need a $parameter to be set in the view too (so, yes $this->view->parameter ...) or you can set in volt, e.g.

{% set parameter  = {'key1':'value1', 'key2':'value2'} %}

I had tried exactly what you have said here, but it doesn't work, maybe I've not done everything I need I get the Exception:

Phalcon\Mvc\View\Exception: Macro `customService` does not exist

edited Jan '16

Oh, sorry. You are right. Previous example doesn't work for custom functions. The correct way: If you planing to use this function in views only, you skip adding to di and just add custom function to volt compiler.

$di->set('voltService', function($view, $di) {

    $volt = new Phalcon\Mvc\View\Engine\Volt($view, $di);
    $compiler = $volt->getCompiler();
    $compiler->addFunction('customService', function($parameter) {
                        //do something with parameter to get rval
                        return $rval;
       });
}