Render view to string, then output json in cakephp
Yes! You Can render a view into a variable. You just have to create a view object .Inside Your Controller Try This:
$view = new View($this,false);$view->viewPath='Elements'; // Directory inside view directory to search for .ctp files$view->layout=false; // if you want to disable layout$view->set ('variable_name','variable_value'); // set your variables for view here$html=$view->render('view_name'); // then use this $html for json response
For those of you using CakePhp3
$view = new View($this->request,$this->response,null);$view->viewPath='MyPath'; // Directory inside view directory to search for .ctp files$view->layout='ajax'; // layout to use or false to disable$html=$view->render('view_name');
Don't forget to add this in your namespace
use Cake\View\View;
The Controller::render()
function actually sets the body of the response by calling CakeResponse::body()
and then returning the current CakeResponse
object. This means that you can call the render()
method inside the controller action, capture its return value and then again call the CakeResponse::body()
and thus replacing the response body with the desired output.
Example code:
$data = $this->paginate();// Pass the data that needs to be used in the view$this->set(compact('data', 'foci', 'jobTypes', 'count_number'));if($this->request->is('ajax')) { // Disable the layout and change the view // so that only the desired html is rendered $this->layout = false; $this->view = 'VIEW_PASSED_AS_JSON_STRING'; // Call the render() method returns the current CakeResponse object $response = $this->render(); // Add any other data that needs to be returned in the response // along with the generated html $jsonResponse = array( 'html' => $response->body(), 'other_data' => array('foo' => 'bar'), 'bar' => 'foo' ); // Replace the response body with the json encoded data $response->body(json_encode($jsonResponse));}