Controller不会在View for Zend Framework中传递变量

时间:2015-08-10 16:49:59

标签: php zend-framework model-view-controller

所以我开始学习Zend Framework 1,并在View中传递值时遇到了一些问题。我在IndexContoller中创建了一个简单的变量,如下所示:

class IndexController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        $this->view->content = "Lorem ipsum";
    }


}

然后我用这样的布局调用它:

<div class="carousel-caption">
  <h2><?php echo $this->layout()->content; ?></h2>
</div>

当我执行var dump

时,它什么都不返回
var_dump($this->layout()->content)

我得到了回复:

string(0) ""

如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

应在布局中使用此$this->layout()->content来呈现在特定于操作的视图中生成的输出。通常,许多特定于操作的.phtml文件将使用common layout

如果您想将某些内容从控制器传递到视图,您可以在控制器上使用$this->foo = 'bar',然后使用echo $this->foo在视图中呈现它;

我还发现了这个可能回答你问题的现有帖子:Sending variables to the layout in Zend Framework - 它解释了布局和视图的重叠和共性。如果你觉得这是一个骗局,由你决定......

答案 1 :(得分:0)

ZF1使用变量content来捕获视图的结果并传递给布局。我猜测您的index.phtml视图为空,这就是您从$this->layout()->content获取空字符串的原因。

如果您想将一些数据传递给布局,请将其正常分配给视图对象,但将其称为“内容&#39; 以外的任何内容:

public function indexAction()
{
    $this->view->foo = "Lorem ipsum";
}

然后在您的布局中,像访问普通视图变量一样访问它:

<div class="carousel-caption">
  <h2><?php echo $this->foo; ?></h2>
</div>

答案 2 :(得分:0)

我同意ficuscr的回答。

但是如果真的需要从控制器设置一些布局值,这个丑陋的黑客可能会对你有用:

$this->_helper->layout()->foo = "value";