0
votes

I have a layout file as follows:

<?php echo $this->doctype(); ?>
<html>
    <head>
        <?php echo $this->headTitle(); ?>
        <?php echo $this->headLink(); ?>
    </head>
    <body>
        <?php echo $this->layout()->content; ?>
    </body>
</html>

I have a menu system which is written in another template

<p>
    <div>
        menu code goes here
    </div>
    <p>
        <?php echo $this->actionContent; ?>
    </p>
</p>

I wanted the action method's output should be placed in $this->actionContent and all of that should go to the layout.

Then I wrote a Controller plugin as follows:

class ZFExt_Controller_Plugin_Addmenu extends Zend_Controller_Plugin_Abstract 
{
    public function postDispatch(Zend_Controller_Request_Abstract $request)
    {
        $view = Zend_Controller_Front::getInstance()
                      ->getParam('bootstrap')
                      ->getResource('view');

        if (false !== $request->getParam('menu'))
        {
            $response = $this->getResponse();
            $content = $response->getBody(true);
            $view->menuContent = $content['default'];
            $updatedContent = $view->render('menu.phtml');
            $response->setBody($updatedContent);
        }
    }
}

In the controller class

class IndexController extends Zend_Controller_Action {


    public function indexAction() {

    }

    public function viewAction()
    {
          $this->getRequest()->setParam('menu', false);
    }
}

So whichever action does not want the menu there we can pass a parameter 'menu' with value 'false'.

My question is: Is this the right way to do ?

1
You can use zend navigation to do thatShaolin

1 Answers

1
votes

First, I probably wouldn't render the menu from an action. I tend to think of actions as corresponding to HTTP requests, building full pages/responses, rather than just page fragments, for the waiting client. I would either have a separate class/component handle menu creation or just use Zend_Navigation.

Beyond that, if I understand correctly, you simply want each action to be able to enable/disable the menu portion of the layout, right?

So, how about simply setting a switch in the view that enables/disables the menu in the layout.

The layout looks like:

<?php echo $this->doctype(); ?>
<html>
    <head>
        <?php echo $this->headTitle(); ?>
        <?php echo $this->headLink(); ?>
    </head>
    <body>
        <?php if ($this->renderMenu): ?>
            // render menu here 
        <?php endif; ?>
        <?php echo $this->layout()->content; ?>
    </body>
</html>

Then in your action, if you want to disable the menu rendering, you can set:

$this->view->renderMenu = false;

Probably also worthwhile to set a default value for the $view->renderMenu flag at some point in the request dispatch cycle - perhaps at bootstrap, or in a controller plugin, or in controller init().