Search code examples
phpzend-frameworkzend-framework2zend-framework-mvc

How to render a page in zend framework 2?


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');

Solution

  • Actually what you have done should work with following miner changes

    public function userinforeceiveAction()
    {   
        $renderer = new PhpRenderer();
    
        $map = new Resolver\TemplateMapResolver(array(
        // first mistake
        // __DIR__ is the directory of application controller, not the path of views 
        // second mistake
        // 'userinfo' should be '(controller)/(action)'
        'userinfo' => __DIR__ . '/userinfo.phtml',
            ));
    
            // third mistake
            // since $map is a resolver instance, this is wrong
            $resolver = new Resolver\TemplateMapResolver($map); // no need
            $renderer->setResolver($resolver);
            // should be $renderer->setResolver($map);
            $model = new ViewModel();
            // 'userinfo' should be changed
            $model->setTemplate('userinfo');
    
            // big mistake
            // what you are returning here is new instance of view model
            return new ViewModel();
            // instead you should return $model 
    }
    

    No need of this line within the view

    echo $renderer->render($model);
    

    But the best and recommended way is to inject through the module configuration file, as Adam said

    The documentation will provide better explanation