开发者

CakePHP - Just Layout?

I want to set $this->layout to json in the controller action.

In the json layout, there will be a line saying $this->Javascript>object(); which will parse through the data given to it by the controller, and output the jS开发者_C百科ON.

However, creating a new view file for each jSON request, eg. recipe_view, ingredient_view isn't necessary, I just need a layout.

Is there a way to bypass the view file altogether and have just the layout, without the notorious Missing View! error?


@pleasedontbelong's solution works. You can also create a layout and view for ajax.

Your layout can be something like this:

<?php echo $content_for_layout;?>

And then you can create an ajax view like this:

<?php echo $this->Js->object($result);?>

And then from your controller...

public function savecontent(){
    $this->autoRender = false;
    $this->set('result', false);

    if(!empty($this->data)){
        $data = $this->data;

        //Do something with your data

        //send results to view
        $this->set('result', $myNewData);
    }

    $this->render(null, 'ajax','/ajax/ajax');
}


hmmm it should be something like this: (not tested)

function action(){
    $this->autoLayout = $this->autoRender = false;

     // your code

    $this->render('/layouts/json');
}

Hope this helps


In config/routes.php:

Router::parseExtensions('json');

In app_controller.php:

var $components = array('RequestHandler');
var $helpers = array('Js');

function render($action = null, $layout = null, $file = null) {
    switch($this->RequestHandler->ext) {
        case 'json':
            Configure::write('debug', 0);
            return parent::render(null, 'default', '/json');
        default:
            return parent::render($action, $layout, $file);
    }
}

In views/json.ctp:

<?php echo $this->Js->object(isset($data) ? $data : array()); ?>

In views/layouts/json/default.ctp:

<?php
header('Cache-Control: no-store, no-cache, max-age=0, must-revalidate');
header('Content-Type: application/json');
echo $content_for_layout;
?>

In the controller action you want to output json:

$this->set('data', array('foo' => 'bar'));

Now every call to an action with the .json extension (www.example.com/posts/view/12.json) will output a json object without having to call the render function in each action.


This has been made SUPER easy with CakePHP 2.1. See documentation here.

  1. In your AppController, add this line after the class has been declared:

    public $viewClass = 'Json';

  2. Next, add this line to the end of your Controller action, including any data you would like displayed in json format:

    $this->set(compact(array('dataSet1', 'dataSet2')));

    $this->set('_serialize', array('dataSet1', 'dataSet2'));

And that's it! You don't need a view set up for this. And even if you had one set up, CakePHP would ignore it and just display the variables you indicated in the '_serialize' array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜