How to disable layout and view renderer in ZF2?

2019-01-23 12:10发布

How can i disable layout and view renderer in Zend Framework 2.x? I read documentation and can't get any answers looking in google i found answer to Zend 1.x and it's

$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout->disableLayout();

But it's not working any more in Zend Framework 2.x. I need to disable both view renderer and layout for Ajax requests.

Any help would be great.

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-23 12:51

Just use setTerminal(true) in your controller to disable layout.

This behaviour documented here: Zend View Quick Start :: Dealing With Layouts

Example:

<?php
namespace YourApp\Controller;

use Zend\View\Model\ViewModel;

class FooController extends AbstractActionController
{
    public function fooAction()
    {
    $viewModel = new ViewModel();
    $viewModel->setVariables(array('key' => 'value'))
              ->setTerminal(true);

    return $viewModel;
    }
}

If you want to send JSON response instead of rendering a .phtml file, try to use JsonRenderer:

Add this line to the top of the class:

use Zend\View\Model\JsonModel;

and here an action example which returns JSON:

public function jsonAction()
{
    $data = ['Foo' => 'Bar', 'Baz' => 'Test'];
    return new JsonModel($data);
}

EDIT:

Don't forget to add ViewJsonStrategy to your module.config.php file to allow controllers to return JSON. Thanks @Remi!

'view_manager' => [
    'strategies' => [
        'ViewJsonStrategy'
    ],
],
查看更多
霸刀☆藐视天下
3楼-- · 2019-01-23 12:51

Slightly more info on the above answer... I use this often when outputting different types of files dynamically: json, xml, pdf, etc... This is the example of outputting an XML file.

// In the controller
$r = $this->getResponse();

$r->setContent(file_get_contents($filePath)); //

$r->getHeaders()->addHeaders(
    array('Content-Type'=>'application/xml; charset=utf-8'));

return $r;

The view is not rendered, and only the specified content and headers are sent.

查看更多
够拽才男人
4楼-- · 2019-01-23 12:58

You can add this to the end of your action:

return $this->getResponse();
查看更多
登录 后发表回答