How to disable layout and view renderer in ZF2?

后端 未结 3 978
爱一瞬间的悲伤
爱一瞬间的悲伤 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:37

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

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

    Example:

    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'
        ],
    ],
    

提交回复
热议问题