2012-08-24 38 views
16

如何呈現控制器操作中默認以外的其他視圖。默認情況下,它嘗試在視圖文件夾中查找與操作相同的視圖,但我希望在視圖文件夾中爲控制器操作呈現不同的視圖。如何在ZF2的控制器操作中呈現不同的視圖

我們可以做到這一點ZF1這樣$this->_helper->viewRenderer('foo');

任何人都可以知道,如何在Zendframework 2實現上述?

我們可以禁用使用

$response = $this->getResponse(); 
     $response->setStatusCode(200); 
     $response->setContent("Hello World"); 
     return $response; 

我不知道如何更改視圖/渲染ZF2不同的看法。

回答

44

可以使用

public function abcAction() 
{ 
    $view = new ViewModel(array('variable'=>$value)); 
    $view->setTemplate('module/controler/action.phtml'); // path to phtml file under view folder 
    return $view; 
} 

由於需做akrabat覆蓋幾乎每一個場景。

+1

HTTP路由和view_manager:// zf2test.akrabat.com/ – Developer

+1

https://github.com/akrabat/ZF2TestApp/blob/master/module/Application/config/module.config.php#L78 – Developer

+0

+1,完美答案!!! – SagarPPanchal

2

我在Zend Framewor 2中的解決方案很簡單。對於索引我傾向於致電parrent :: indexAction()構造函數bcs我們擴展Zend \ Mvc \ Controller \ AbstractActionController。或者只是在indexAction中返回數組()()。 ZF將自動返回index.pthml,確定必須返回的內容。

返回新ViewManager()相同返回陣列()

<?php 

namespace Test\Controller; 

use Zend\Mvc\Controller\AbstractActionController, 
    Zend\View\Model\ViewModel; 

// Or if u write Restful web service then use RestfulController 
// use Zend\Mvc\Controller\AbstractRestfulController 

class TestController extends AbstractActionController 
{ 
    /* 
    * Index action 
    * 
    * @return main index.phtml 
    */ 

    public function indexAction() 
    { 
      parent::indexAction(); 

      // or return new ViewModel(); 
      // or much simple return array(); 
    } 

    /* 
    * Add new comment 
    * 
    * @return addComment.phtml 
    */ 

    public function addAction() 
    { 
     $view = new ViewManager(); 
     $view->setTemplate('test/test/addComment.phtml'); // module/Test/view/test/test/ 

     return $view; 
    } 

不要忘記配置在模塊/配置/ module_config

'view_manager' => array(
     'template_path_stack' => array(
      'Test' => __DIR__ . '/../view', 
     ), 
    ), 
相關問題