Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render view to string, then output json in cakephp

I am facing some problems with CakePHP 2.4 in the moment while working with AJAX and JSON.

I want to render data with a view, but save the resulting html as a string in a variable. After that, I would like to set an array, containing this html string among other data to return as JSON object. Unfortunately I didn't find the right way yet.

My controller code so far makes use of the CakePHP json magic:

//Controller (just parts) 

$data = $this->paginate();

if($this->request->is('ajax')) {

        $jsonResponse = array(

            'jobs' => $data,

            'foci' => $foci,

            'jobTypes' => $jobTypes,

            'count_number'=> $count_number

        );

        $this->set('jsonResponse', $jsonResponse);

        $this->set('_serialize', 'jsonResponse');

    } else {

        // render regular view
        $this->set(compact('data', 'foci', 'jobTypes', 'count_number'));

    }

This outputs the perfect json in the javascript console, besides the fact, that the data in $data is plain data.

Is it somehow possible, to pass $data to a view, render it, save the output to a string variable $html, and pass $html to jobs in jsonResponse instead of $data?

like image 969
zinky Avatar asked May 05 '14 08:05

zinky


2 Answers

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
like image 60
Spandan Singh Avatar answered Oct 11 '22 23:10

Spandan Singh


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;
like image 26
Franz Avatar answered Oct 11 '22 22:10

Franz