How to disable layout and view renderer in ZF2?

后端 未结 3 972
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-15 18:01

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

相关标签:
3条回答
  • 2020-12-15 18:17

    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.

    0 讨论(0)
  • 2020-12-15 18:37

    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'
        ],
    ],
    
    0 讨论(0)
  • 2020-12-15 18:41

    You can add this to the end of your action:

    return $this->getResponse();
    
    0 讨论(0)
提交回复
热议问题