2012-02-01 41 views
4

我想與Zend框架做的是從動作X渲染動作Y和獲得HTML:ZF渲染的動作,並取得HTML在另一個行動

例子:

public xAction(){ 
    $html = some_function_that_render_action('y'); 
} 

public yAction(){ 
    $this->view->somedata = 'sometext'; 
} 

其中y的看法是這樣的:

<h1>Y View</h1> 
<p>Somedata = <?php echo $this->somedata ?></p> 

我發現那位動作助手,但我不能從一個控制器使用。我該如何解決它? 有可能嗎?

+0

ZF是否支持'partials'?讓xAction和yAction調用其特定模板,並在這些特定模板中調用共享的部分模板。 – 2012-02-01 17:55:12

回答

2

這裏有一種可能的方式來做你想做的事。

public function xAction() 
{ 
    $this->_helper 
     ->viewRenderer 
     ->setRender('y'); // render y.phtml viewscript instead of x.phtml 

    $this->yAction(); 

    // now yAction has been called and zend view will render y.phtml instead of x.phtml 
} 

public function yAction() 
{ 
    // action code here that assigns to the view. 
} 

除了使用ViewRenderer設置使用的視圖腳本,你也可以撥打yAction正如我上面顯示,但通過調用$html = $this->view->render('controller/y.phtml');

又見ActionStack helper得到的HTML。

+0

您的第一個解決方案不能解決我的問題:它改變了操作的視圖,但我只需要html。 – 2012-02-02 09:25:31

+0

您的第二個解決方案返回html,但不要將正確的數據分配給視圖(不要調用操作)。 – 2012-02-02 09:26:40

0

最後我發現這個「解決方案」,這不是我想要做的,但它的工作原理,如果有人找到真正的解決方案,請在這裏回答。

public function xAction(){ 
    $data = $this->_prepareData(); 
    $view = new Zend_View(); 
    $view->somedata = $data; 
    $view->setScriptPath($this->view->getScriptPaths()); 

    $html = $view->render('controller/y.phtml'); 
} 
+0

調用新的Zend_View()重置視圖,並且在其他文件夾和命名空間中註冊的幫助器必須重新定義 – 2014-01-20 11:15:02

1

您可以從控制器

public function xAction() 
{ 
    $html = $this->view->action(
     'y', 
     $this->getRequest()->getControllerName(), 
     null, 
     $this->getRequest()->getParams() 
    ); 
} 

public function yAction() 
{ 
    // action code here that assigns to the view. 
} 

使用動作視圖助手這不是很漂亮,但它工作得很好,你不必使用$view->setScriptPath($this->view->getScriptPaths());

此幫助創建一個新的Zend_Controller_Request for yAction(),所以你可以給你自己的參數作爲第四個參數或者使用$this->getRequest()->getParams()來傳播xAction()的請求參數。

http://framework.zend.com/manual/1.12/en/zend.view.helpers.html#zend.view.helpers.initial.action