2012-05-03 82 views
4

我使用下面的代碼在控制器操作中呈現頁面。如何在zend框架2中呈現頁面?

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();  
} 

和我在視圖中迴應渲染內容。

echo $renderer->render($model); 

但它什麼也不渲染。請幫幫我。謝謝。 以及這兩條線與zf1的良好合作。

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

回答

2

你做了什麼其實應該配置有下列礦工工作的變化

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 
} 

認爲

echo $renderer->render($model); 

內不需要此行,但最好和推薦的方法是通過模塊配置文件注入, 爲Adam

documentation將提供更好的解釋

1

你可能想看看skeleton application關於如何在MVC環境中渲染東西。

主要是你正確地做它。但是,爲什麼你不使用它創建渲染器和解析器?我想設置一個渲染策略和模板?這不是在控制器中完成的,而是在應用程序/模塊的配置中完成的。

另一方面,您不會在視圖中回報渲染器的結果 - 渲染器會返回視圖的結果,然後由應用程序回顯您的視圖的結果(您不這樣做由你自己)。

+0

可以幫助更多的東西。我不太瞭解。 –

+0

你應該在你的問題上更具體一些,然後閱讀文檔並運行並嘗試框架應用程序。 – Fge

9

如果您使用的是ZF2的MVC層,你不需要實例化自己的視圖呈現,只返回一個視圖模型實例,並會照顧其餘的:

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

有關如何爲例使用視圖模型看Akrabat的ZF2TestApp:http://zf2test.akrabat.com/

相關的ZF2代碼在該頁面的底部和模板地圖鏈接在module configuration file