Zend捕获布局并将内容视为变量

时间:2014-05-15 16:33:23

标签: zend-framework view

我有一个控制器Mycontroller,带有简单的例行操作:

public function exempleAction(){
    // Using layout "mail"
    $this->_helper->layout()->setLayout("mail");
}

我希望使用以下内容获取视图的HTML内容:(稍后将其用作电子邮件内容)

$view_helper  = new Zend_View_Helper_Action();
$html_content = $view_helper->action('exemple', 'Mycontroller','mymodule');

这成功地允许我获取视图内容,但没有布局内容。布局“mail”的所有HTML代码都不包含在$ html_content中。

如何捕获整个内容,包括布局部分?

2 个答案:

答案 0 :(得分:1)

如果我没有弄错的话,$view_helper->action('exemple', 'Mycontroller','mymodule');

之后您没有布局是正常的

的确,布局是在Zend_Layout_Controller_Plugin_Layout插件的postDisatch()中调用的。

你仍然可以试试这个:

在你的布局' mail.phtml'把这个:

echo $this->layout()->content;

在你的方法中:

$view_helper = new Zend_View_Helper_Action();
$html_content = $view_helper->action('exemple', 'Mycontroller','mymodule');

$layout_path = $this->_helper->layout()->getLayoutPath();
$layout_mail = new Zend_Layout();
$layout_mail->setLayoutPath($layout_path) // assuming your layouts are in the same directory, otherwise change the path
            ->setLayout('mail');

// Filling layout
$layout_mail->content = $html_content;
// Recovery rendering your layout
$mail_content = $layout_mail->render();
var_dump($mail_content);

答案 1 :(得分:0)

试试这个:

//this will get the current layout instance
//clone it so you wont see any effects when changing variables
$layout = clone(Zend_Layout::getMvcInstance());

//if you want to use another layout script at another location
//$path = realpath(APPLICATION_PATH . '/../emails/');
//$layout->setLayoutPath($path);

//set the layout file (layout.phtml)
//$layout->setLayout('layout');

//prevent this layout from beeing the base layout for your application
$layout->disableLayout();

//get your view instance (or create a new Zend_View() object)
$view = $this->view; //new Zend_View();

//set the path to view scripts if newly created and add the path to the view helpers
//$view->setBasePath(realpath(APPLICATION_PATH.'/../application/emails')."/");
//$view->addHelperPath(realpath(APPLICATION_PATH.'/../application/layouts/helpers/')."/", 'Application_Layout_Helper');

//set some view variables if new view is used (used in the view script $this->test)
$view->assign('test', 'this can be your value or object');

//set the content of your layout to the rendered view
$template = 'index/index.phtml';
$layout->content = $view->render($template);


$bodyHtml = $layout->render();
Zend_Debug::dump($bodyHtml);

在您的操作中获取响应正文。 这将存储通常作为响应发送到浏览器的html。

//first disable output if needed
$this->view->layout()->disableLayout();
//get the response object
$response = $this->getResponse();

$bodyHtml = $response->getBody();
Zend_Debug::dump($bodyHtml);

玩得开心!