Different views for a same action

Hi,

I usually need 3 different views for a same action: one classical html view, one javascript view (i.e. including JS widgets like dynamic grids) and one json view (i.e. feeding the JS widgets with a REST service). To realize this, I generally write this at the end of my controller methods:




switch ($format) {

            case 'htm':

                $this->render('view_htm', array(

                    'model' => $model,

                ));

                break;

            case 'js':

                $this->render('view_js');

                // no model -> data are fetched by the javascript

                break;

            case 'json':

                $this->renderPartial('view_json', array(

                    'model' => $model,

                ));

                break;

            default:

                break;

        }



What do you think about this approach which is quite different from the approach taken in this tutorial: http://www.yiiframework.com/wiki/175/how-to-create-a-rest-api

Sincerely,

Fabrice

What are the contents of view_json etc? I would just do


echo json_encode($data);

Yii::app()->end();

Yes, that’s it eirikhm,

I use ‘echo CJSON::encode($model);’

Note that, in the controller, I have to use ‘renderPartial’ to avoid json data to be displayed in the site template/layout.

Fabrice