Ondrej Rafaj
Ondrej Rafaj

Reputation: 4417

Reusing one view for all methods in CakePHP controller

I am building web service using CakePHP and I would like to use one view called output.ctp for all my controller methods. So far I found out that I can have only one view that has to have the same name as the method itself.

I am doing this as I have a highly specific code in the output template that needs to be present in every json file I send out ... anyone can help? :)

Upvotes: 1

Views: 659

Answers (1)

Ross
Ross

Reputation: 17977

$this->render('output'); in any method will force that view to be rendered instead, regardless of method name.

Or $this->render('/OutputController/output'); from outside of the views controller.

An element might be a better choice though, depending on what you are trying to achieve.

i.e.

//output controller
$this->render('output');

//posts controller
$this->render('/Output/output');

Edit: Troubled class working

<?php

class AdminApiController extends AppController {

    var $uses = array('Post', 'User', 'Application'); 

    public function posts() {
        $this->layout = 'ajax';
        $this->set('data', $this->Post->find('all'));
        $this->render('/Api/output');
    }

    public function user() {
        $this->layout = 'ajax';
        $id = $this->Auth->user('id');
        $this->User->id = $id;
        $this->request->data = $this->User->read(null, $id);
        unset($this->request->data['User']['password']);
        unset($this->request->data['User']['password_token']);
        $this->set('data', $this->request->data['User']);
        $this->render('/Api/output');
    }

    public function applications() {
        $this->layout = 'ajax';
        $this->set('data', $this->Application->find('all'));
        $this->render('/Api/output');
    }

Upvotes: 3

Related Questions