Sunday, March 13, 2022

[FIXED] CakePHP3 Render View to a Variable

Issue

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?


Solution

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


Answered By - Reactgular

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.