trOnGAtE

Returning Views Output As A Variable
There are times when you may wish to have the contents of a view file made available as a PHP variable - more specifically a string, instead of being immediately sent to the viewport. We can do this by simply adding , true onto the end of our 'view' command. For example:
function _get_information() {
//create an array of cities
$cities[] = 'New York';
$cities[] = 'London';
$cities[] = 'Paris';
//add 'cities' onto data array​
$data['cities'] = $cities;
//add 'today' onto data array
$data['today'] = 'Monday';
//return the view contents as a string​
$html = $this->view('information', $data, true);
return $html;
}
The idea of calling a view file but not displaying the view file on the screen may seem a little unusual - and it is! However, occasionally, developers have a need to capture the contents that have been generated from a view file - without sending those contents to the browser. One example of such a scenario would be if you were building a feature for caching web pages.
There are three steps required to make your view file contents available as a normal PHP variable:
STEP 1: Add a variable plus an equals symbol before calling the view method. For example:
$output = $this->view('greeting', $data...
STEP 2: Pass the boolean of true into your view as the third argument. For example:
$output = $this->view('greeting', $data, true);
STEP 3: Finally, end your method by returning the variable that you have now created. For example:
return $output;
$code = $this->view('file', [], true);
Once you've created your method for generating view output as a variable, you can easily call your variable - using just one line of ordinary PHP. For example:
$info = $this->_get_information();
//now do something with the info!
HELP & SUPPORT
If you have a question or a comment relating to anything you've see here, please goto the Help Bar.