【问题标题】:Reusing one view for all methods in CakePHP controller在 CakePHP 控制器中为所有方法重用一个视图
【发布时间】:2013-10-26 20:37:39
【问题描述】:

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

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

【问题讨论】:

    标签: php templates cakephp cakephp-2.0


    【解决方案1】:

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

    【讨论】:

    • 太好了,谢谢...当系统允许我这样做时(8分钟)会接受...:)
    猜你喜欢
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    相关资源
    最近更新 更多