CodeIgniter Forums
How to properly get the view as a string - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: How to properly get the view as a string (/showthread.php?tid=80757)



How to properly get the view as a string - Jag81 - 12-14-2021

Hi all, 
My goal is to get a piece of (rendered) HTML code inside a JSON response.  Something like that:
Code:
{
"status": "success",
"html" : "<h1>Today is your birthday</h1>"
}

This is just an example, the real HTML is a little bit longer and has variables inside, so I need to create a view file.

In CI3 there is the third param flag this command to output the HTML as a string:
PHP Code:
$string $this->load->view('you_view'$paramsTRUE); 

Now, I'm trying to understand how things are working in CI4 and choose the right way.

This is my code right now. 
Is this the correct way or is there something that I'm missing (like the View Renderer)?
PHP Code:
$data = [
      'api' => $this->api
      'formId' => $this->formId
];

$html view('form_view'$data);

return 
$this->response->setJSON([
            'status'            => 'success',
            'html'              => $html
        
]); 

Thanks for the advice.


RE: How to properly get the view as a string - kenjis - 12-14-2021

It is the correct way. view() returns string value.

If you want to remove the debug code in the string:
PHP Code:
view('form_view'$data, ['debug' => false]); 



RE: How to properly get the view as a string - InsiteFX - 12-15-2021

You get the view in the same way that you did it with CI 3.

PHP Code:
$viewStr view('your_view'$data); 


Let us know how you make out with this.