Manual says I can use services by its names right in the Volt templates "If a service container (DI) is available for Volt". I believe it should be available if I pass it to Volt constructor. But any service name emits warning about not found variable.
Volt registration code:
$this->set('volt', function ($view, $di) {
$volt = new Volt($view, $di);
print_r($di); // print is ok here
$opt = [
'compiledPath' => APP_ROOT . '/cache/volt/',
'compiledExtension' => '.compiled'
];
if ($this->settings->dev) {
$opt['stat'] = true;
$opt['compileAlways'] = true;
}
$volt->setOptions($opt);
return $volt;
});
$this->set('view', function() {
$view = new View();
$view->setViewsDir($this->settings->dir->view);
$view->setDI($this); // added this line for debug – still doesn't work
$view->registerEngines([
'.volt' => 'volt'
]);
return $view;
});
Let's say I want to use service config
in Volt:
$this->set('config', function() {
return $this->settings;
});
{{ dump(config) }}
{{ dump(di.get("config")) }}
which compiles to
<?php echo var_dump($config); ?>
<?php echo var_dump($di->get('config')); ?>
But I got error Undefined variable: config in ...
and Undefined variable: di in ...
/ Call to a member function get() on null in ...
respectively.
So it looks like DI is not available for Volt. How to fix it?
Don't know if this related information, but I extended FactoryDefault DI container:
class DI extends FactoryDefault
{
/** @var Config $settings */
private $settings;
function __construct(Config $config)
{
parent::__construct();
$this->settings = $config;
// all services declarations go here
}