Mohamed Sharaf

Zend Framework 2: return a response without a view or layout

Two ways to skip rendering in a ZF2 controller action: return the response, or render without the layout.

· 1 min read

From the archive: first published on mohamedsharaf.net in October 2012. Rewritten and checked in 2026; some details may be out of date.

Sometimes a controller action shouldn’t render a template at all, for example when it returns a file, a redirect or raw JSON. In Zend Framework 2 you have two options:

Skip the view completely

public function exportAction()
{
    $response = $this->getResponse();
    $response->setContent($csv);
    return $response;   // returning the Response object skips rendering
}

Render the view, but without the layout

public function partialAction()
{
    $view = new ViewModel(['items' => $items]);
    $view->setTerminal(true);   // no layout around it
    return $view;
}

Today: Zend Framework 2 lives on as Laminas MVC, where both techniques work the same way. For JSON, a JsonModel is usually cleaner.

ShareWhatsAppLinkedInXTelegramFacebook