如何捕获 Zend 视图输出而不是实际输出它
问题:有时在我们的 zend 控制器中,我们不希望直接输出脚本,而是想要该脚本的内容。一个例子:当我们需要将视图脚本的 html 输出结果包含在另一种结构(如 JSON 或 XML)中以便在客户端进行处理时。
我在堆栈溢出处找到了结果,但没有那么快,因为它处于不同的上下文中。我已经为此苦苦挣扎了两天了。事实证明这非常简单:
// 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);
我希望这很清楚并且对某人有用。
Problem: sometimes in our zend controller we don't want the script to be output directly, but rather want the content of that script. One example: when we need the result html output of a view script be included in another structure like JSON or XML for processing in the client side.
I found the result here at stack overflow, but not so quick since it was in a different context. I have been struggling with this for 2 days now. As it turned out it was very simple:
// 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);
I hope this was clear and will be useful to somebody.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用
Json action Helper 通常会
viewRenderer
json_encode
数组Try using
The Json action Helper will normally
viewRenderer
json_encode
the array