如何捕获 Zend 视图输出而不是实际输出它

发布于 2024-09-25 02:30:48 字数 703 浏览 10 评论 0原文

问题:有时在我们的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

云朵有点甜 2024-10-02 02:30:48

尝试使用

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

Json action Helper 通常会

  • 禁用 viewRenderer
  • 禁用布局
  • json_encode 数组

Try using

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

The Json action Helper will normally

  • disable the viewRenderer
  • disable the layout
  • json_encode the array
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文