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

Volt engine in user Component

Hi guys!

I want to use Volt in my Component, but have some issues with this. I have a Elements component like in invo (https://github.com/phalcon/invo/blob/master/app/library/Elements.php), but I want to render partials templates.

class Elements extends ComponentBase
{
    public function getMenu()
    {
        $someData = array();
        echo $this->render('partials/menu', array('someData' => $someData));
    }
}

class ComponentBase extends Phalcon\Mvc\User\Component
{
    protected function render($templateName, $params=null)
    {
        $view = new Phalcon\Mvc\View\Simple();
        $view->setViewsDir(__DIR_.'/../views/');
        return  $view->render($templateName, $params);
    }
}

It's work for me (template file extension is ".phtml"). But if I want to use Volt (template file extension is ".volt"):

class ComponentBase extends Phalcon\Mvc\User\Component
{
    protected function render($templateName, $params=null)
    {
        $view = new Phalcon\Mvc\View\Simple();
        $view->setViewsDir(__DIR_.'/../views/');
        $view->registerEngines(array(
            ".volt" => function($view, $di) {
                $volt = new Phalcon\Mvc\View\Engine\Volt($view, $di);
                 return $volt;
            }
        ));
        return  $view->render($templateName, $params);
    }
}

I get error "A dependency injector container is required to obtain the application services".

Need help. Thanks



98.9k

You need to pass the dependency injector to the Phalcon\Mvc\View\Simple instance.

$view = new Phalcon\Mvc\View\Simple();
$view->setDI($this->di);