为CakePHP控制器中的所有方法重用一个视图

时间:2013-10-26 20:37:40

标签: php templates cakephp cakephp-2.0

我正在使用CakePHP构建Web服务,我想为所有控制器方法使用一个名为output.ctp的视图。到目前为止,我发现我只能有一个视图必须与方法本身具有相同的名称。

我这样做是因为我在输出模板中有一个高度特定的代码,需要出现在我发出的每个json文件中...任何人都可以提供帮助吗? :)

1 个答案:

答案 0 :(得分:3)

无论方法名称如何,任何方法中的

$this->render('output');都会强制渲染该视图。

或来自视图控制器外部的$this->render('/OutputController/output');

元素可能是更好的选择,具体取决于您要实现的目标。

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

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

编辑:陷入困境的班级工作

<?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');
    }