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

Accesing DI service injection in volt

$di = new \Phalcon\Di\FactoryDefault();

//Register Volt as a service
$di->set('voltService', function($view, $di) {
    $volt = new Volt($view, $di);
    $volt->setOptions(array(
            "compiledPath" => function($templatePath) {
                return '../app/compiled-templates/' .basename($templatePath,'.volt')  . '.php';},
            "compiledExtension" => ".compiled",
            "compiledSeparator" => "_"
    ));
    return $volt;
});
//Register Volt as template engine
$di->set('view', function() {
    $view = new SimpleView();
    $view->setViewsDir('../app/views/');
    $view->registerEngines(array(
        ".volt" => 'voltService'
    ));
    return $view;
});
//injecting service - xconfig
$di->set('xconfig', function () {
    $data = array(
        'domain' => 'example.com',
    );
    return $data;
});

Retreiving this in volt

{{ dump(this.di.get('xconfig')) }} // works
{{ dump('xconfig') }} // doesnt work

How do I access xconfig directly in volt? Is it possible? This is the closest approach I have been able to think of

{% set xconfig = this.di.get('xconfig') %} // set var from di
{{ dump(xconfig) }} // access throughout the volt with the new var


58.3k

Hey man

You just to call

this.xconfig
edited Aug '15

in this url https://docs.phalcon.io/en/latest/reference/volt.html#inject-services-into-a-template

{# Inject the 'flash' service #}
<div id="messages">{{ flash.output() }}</div>

I would like xconfig to be something similar (without 'this' keyword)

note - this.xconfig worked for me. Thank you for that approach

Hey man

You just to call

this.xconfig


7.9k

Hi I think that is bad idea to access DI in volt, why you now passing it to volt while you are in controller?

edited Aug '15

Hi I think that is bad idea to access DI in volt, why you now passing it to volt while you are in controller?

Volt is already RUNNING in di, so he already has access to all services in di.

Also only xconfig should work too