CakePHP3将视图呈现为变量

g2ieeal7  于 2022-11-11  发布在  PHP
关注(0)|答案(2)|浏览(172)

我想把视图转换成一个变量,而不是直接发送到浏览器。我曾经用cakephp2.* 做过。但是,我不知道如何在CakePHP3中做这件事。你能告诉我如何做吗?

fcg9iug3

fcg9iug31#

ViewBuilder是在CakePHP 3.1中引入的,它处理视图的渲染。当我想渲染一个变量时,我总是去看看发送电子邮件是如何工作的。
从控制器:

function index() {
     // you can have view variables.
     $data = 'A view variable';

     // create a builder (hint: new ViewBuilder() constructor works too)
     $builder = $this->viewBuilder();

     // configure as needed
     $builder->layout('default');
     $builder->template('index');
     $builder->helpers(['Html']);

     // create a view instance
     $view = $builder->build(compact('data'));

     // render to a variable
     $output = $view->render();
 }
rm5edbpk

rm5edbpk2#

对于 AJAX 请求/响应,我使用以下代码:

public function print(){            
        if ($this->request->is('ajax')) {
            $data = $this->request->getData();
            $builder = $this->viewBuilder()
            ->setTemplatePath('ControllerName')
            ->setTemplate('print');
            ->setLayout('ajax');
            ->enableAutoLayout(false);

            $view = $builder->build(compact('data'));
            $html = $view->render();
            $res =  ['html' => $html];
            $this->set('response',$res);
            $this->set("_serialize",'response'); 
        }
    }

print.ctpTemplate/ControllerName之下

相关问题