Zend Framework – Disable Layout and View from Rendering (Handy for AJAX)

I don’t know how many times I have needed to look this up for myself, typically when I am putting together a controller action that I want to use specifically for outputting something like JSON for some AJAX related thing I am doing. That or when I am working on a page that I need to have different from the base template that I have setup in my layouts. Either way, figured I’d post it here like the rest of the code I tend to reuse often, and share with the world cause they may be looking for it too.

public function indexAction()
{
    $this->_helper->layout()->disableLayout();
    $this->_helper->viewRenderer->setNoRender(true);
}

The two above lines added into just about any “Action” will stop your default layout from loading. Alternatively you could also do it as a pre dispatch for the entire controller like so.

public function preDispatch()
{
    $this->_helper->layout()->disableLayout();
    $this->_helper->viewRenderer->setNoRender(true);
}