【问题标题】:ZF Render an action and get the html in another actionZF 渲染一个动作并在另一个动作中获取 html
【发布时间】:2012-02-01 17:49:26
【问题描述】:

我想用 Zend Framework 做的是从动作 X 渲染动作 Y 并获取 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>

我找到了动作助手,但我无法从控制器中使用它。我该如何解决? 有可能吗?

【问题讨论】:

  • ZF 是否支持'partials'?让 xAction 和 yAction 调用它们的特定模板,在这些特定模板中它们调用共享部分模板。

标签: zend-framework view frameworks action render


【解决方案1】:

这是一种可能的方式来做你想做的事。

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-&gt;view-&gt;render('controller/y.phtml'); 来获取 html

另请参阅ActionStack helper

【讨论】:

  • 你的第一个解决方案不能解决我的问题:它改变了动作的视图,但我只需要 html。
  • 您的第二个解决方案返回 html,但不要将正确的数据分配给视图(不要调用操作)。
【解决方案2】:

您可以从控制器中使用 Action View Helper

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-&gt;setScriptPath($this-&gt;view-&gt;getScriptPaths());

此助手为 yAction() 创建一个新的 Zend_Controller_Request,因此您可以将自己的参数作为第 4 个参数或使用$this-&gt;getRequest()-&gt;getParams() 传播 xAction() 的请求参数。

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

【讨论】:

    【解决方案3】:

    终于找到了这个“解决方案”,这不是我想做的,但它确实有效,如果有人找到了真正的解决方案,请在这里回答。

    public function xAction(){
        $data = $this->_prepareData();
        $view = new Zend_View();
        $view->somedata = $data;
        $view->setScriptPath($this->view->getScriptPaths());
    
        $html = $view->render('controller/y.phtml');
    }
    

    【讨论】:

    • 调用 new Zend_View() 重置视图并且在其他文件夹和命名空间中注册的助手必须重新定义
    猜你喜欢
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    相关资源
    最近更新 更多