CakePHP3 Render View to a Variable
Asked Answered
D

2

5

I want to render the view to a variable without directly sending it to the browser. I used to do it with cakephp2.*. But, I cannot figure out how to do it in CakePHP3. Could you please tell me how to do it?

Destructionist answered 6/11, 2016 at 0:4 Comment(3)
It works the same way, so I'd assume that you either didn't try, or that you already did it the wrong way in 2.x?!Cassette
@ndm, appreciate if you can show me how to do it.Destructionist
Will you please add existing CakePHP 2.x code in your description then it will be more helpfullHear
A
10

ViewBuilder was introduced in CakePHP 3.1 and handles the rendering of views. When ever I want to render to a variable I always go look at how send email works.

From a controller:

 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();
 }
Antisana answered 6/11, 2016 at 13:9 Comment(0)
D
0

For Ajax request/response, I use this:

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

And the print.ctp is under Template/ControllerName

Delindadelineate answered 21/3, 2021 at 11:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.