Zend Framework: Render multiple Views in one Layout

Michi picture Michi · Aug 22, 2009 · Viewed 33.6k times · Source

I want to generate a dynamic site using Zend_Layout.

My layout (/application/layouts/scripts/layout.phtml) contains the following lines:

...        
<body>

        <?php echo $this->render('header.phtml') ?>

        <div id="content"><?php echo $this->layout()->content ?></div>

        <?php echo $this->render('footer.phtml') ?>

    </body>
...

If i browse to my index controller index action - Zend renders the index view (application/views/scripts/index/index.phtml) inside of $this->layout()->content automatically.

Now i want to render the views of to different controller actions in the layout. So i generate a new controller auth with an action login that shows a login form.

I change my layout to:

  ...        
    <body>

            <?php echo $this->render('header.phtml') ?>

            <div id="content"><?php echo $this->layout()->content ?></div>
            <div id="login"><?php echo $this->layout()->login ?></div>

            <?php echo $this->render('footer.phtml') ?>

        </body>
    ...

When i browse to index/index, i want to define in this action that zend should render auth/login view inside $this->layout()->login and for example news/list inside of $this->layout()->content.

index/index is than a kind of a page layout - and auth/login and news/list a kind of widget

How to do this?

Answer

gnarf picture gnarf · Aug 22, 2009

First advice is to avoid the Action view helper at all costs, it will probably be removed in ZF 2.0 anyway. (ZF-5840) (Why the actionstack is evil)

This is related to a question I asked - and bittarman's answer is pretty useful. The best way to implement something like that is to have a view helper that can generate your "login" area. My_View_Helper_Login for instance. Then your layout can call $this->login(), and so can the view script for user/login. As far as having index/index render the content from news/list just forward the request to the other controller/action from the controller. $this->_forward('list', 'news');