如何在 ZF2 中禁用布局和视图渲染器? [英] How to disable layout and view renderer in ZF2?

查看:28
本文介绍了如何在 ZF2 中禁用布局和视图渲染器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Zend Framework 2.x 中禁用布局和视图渲染器?我阅读了文档,但在谷歌中找不到任何答案我找到了 Zend 1.x 的答案,它是

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();

但它在 Zend Framework 2.x 中不再起作用.我需要为 Ajax 请求禁用视图渲染器和布局.

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

任何帮助都会很棒.

推荐答案

只需在控制器中使用 setTerminal(true) 即可禁用布局.

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

此处记录了此行为:Zend View 快速入门 :: 处理布局

示例:

<?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;
    }
}

如果您想发送 JSON 响应而不是呈现 .phtml 文件,请尝试使用 JsonRenderer:

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;

这里是一个返回 JSON 的操作示例:

and here an action example which returns JSON:

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

不要忘记将 ViewJsonStrategy 添加到您的 module.config.php 文件中,以允许控制器返回 JSON.谢谢@Remi!

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

'view_manager' => [
    'strategies' => [
        'ViewJsonStrategy'
    ],
],

这篇关于如何在 ZF2 中禁用布局和视图渲染器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆