CakePHP3将视图渲染为变量

时间:2016-11-06 00:04:14

标签: cakephp cakephp-3.0

我想将视图呈现给变量而不直接将其发送到浏览器。我曾经用cakephp2做过。*。但是,我无法弄清楚如何在CakePHP3中做到这一点。你能告诉我怎么做吗?

2 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:0)

对于 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