2010-09-27 46 views
6

問題:有時在我們的zend控制器中,我們不希望腳本直接輸出,而是需要該腳本的內容。一個例子:當我們需要將結果的HTML輸出視圖腳本包含在另一個結構中,如JSON或XML,以便在客戶端處理時。如何捕獲Zend視圖輸出而不是實際輸出

我在這裏發現堆棧溢出的結果,但不是那麼快,因爲它在不同的上下文中。我一直在爲此掙扎2天。事實證明這很簡單:

// in our controllers' action method 
    $this->_helper->layout()->setLayout('empty'); // disable layout 
    $this->_helper->viewRenderer->setNoRender(true); // make sure the script is not being rendered 

    // any of your code here 
    $html = $this->view->render('projects/climate.phtml'); // return the view script content as a string 
    $json = array('html'=>$html, 'initData'=>'my other needed data'); 
    echo json_encode($json); 

我希望這是清楚的,並將有用的人。

+1

斯拉夫您好。歡迎您在此分享您的知識,但這是一個問答網站。您應該將其作爲評論或回答原始問題發佈。 – takeshin 2010-09-27 17:36:51

+0

這就是我會做的。 – Slavic 2010-10-04 17:09:35

回答

9

嘗試使用

public myAction() { 
    $this->_helper->json(array(
     'html' => $this->view->render('projects/climate.phtml'), 
     'initData'=> 'my other needed data', 
    )); 
} 

JSON動作助手通常

  • 禁用viewRenderer
  • 禁用佈局
  • json_encode陣列
+0

坦克朱利安!你的版本稍微更薄。 – Slavic 2010-10-01 13:14:28