简体   繁体   中英

Controller won't pass a variable in View for Zend Framework

So I started to learn Zend Framework 1 and run in to some problem, with passing a values in a View. I created a simple variable in IndexContoller like this:

class IndexController extends Zend_Controller_Action
{

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

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


}

And then I called it in a layout like this:

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

It returns nothing, when I do var dump

var_dump($this->layout()->content)

I get this back:

string(0) ""

How to fix this?

This $this->layout()->content should be used in your layout to render the output that has been generated in your action specific view. Typically many action specific .phtml files will use a common layout .

If you want to pass something from the controller to the view you would use $this->foo = 'bar' on the controller then render it in your view with echo $this->foo ;

I've also found this existing post that might answer your question: Sending variables to the layout in Zend Framework - It explains the overlap and commonalities of the layout and view. Up to you if you feel that is a dupe...

ZF1 uses the variable content to capture the result of the view and pass to the layout. I'm guessing your index.phtml view is empty which is why you're getting an empty string from $this->layout()->content .

If you want to pass some data to the layout, assign it to the view object as normal, but call it anything other than 'content' :

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

then in your layout, access it like you would a normal view variable:

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

I do agree with ficuscr's answer.

However if you really need to set some layout's value from a controller this ugly hack may work for you:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM