How to render a page in zend framework 2?

Mangala Edirisinghe picture Mangala Edirisinghe · May 3, 2012 · Viewed 9k times · Source

I used below code to render a page in the controller action.

public function userinforeceiveAction()
{   
    $renderer = new PhpRenderer();

    $map = new Resolver\TemplateMapResolver(array(
    'userinfo' => __DIR__ . '/userinfo.phtml',
        ));

        $resolver = new Resolver\TemplateMapResolver($map);
        $renderer->setResolver($resolver);
        $model = new ViewModel();
        $model->setTemplate('userinfo');

        return new ViewModel();    
}

and I echo rendering content in the view.

echo $renderer->render($model);

but it render nothing. Please help me. thanks. and also its fine work with zf1 by this two lines.

$this->userinfoAction();
$this->$render('userinfo');

Answer

Adam Lundrigan picture Adam Lundrigan · Jun 27, 2012

If you are using the ZF2 MVC layer you don't need to instantiate your own view rendering, just return a ViewModel instance and it will take care of the rest:

public function userinforeceiveAction()
{
    $vm = new ViewModel();
    $vm->setTemplate('userinfo');
    return $vm;
}

For an example of how to use view models see Akrabat's ZF2TestApp: http://zf2test.akrabat.com/

The associated ZF2 code is linked at the bottom of that page and the template map is configured in the module configuration file