Rendering controller to a different view in CakePHP

后端 未结 7 1063
长发绾君心
长发绾君心 2021-02-01 16:10

Is there a way to render a controller to a different view then normal? I\'m trying to pass some data from the controller to a non-default view. Meaning my controller is called:<

相关标签:
7条回答
  • 2021-02-01 16:41

    Try to put the name of the view without .ctp extension.

    $this->render('file');
    
    0 讨论(0)
  • 2021-02-01 16:45

    I would rather use:

    $this->view = 'file';
    

    because any $this->set('var', $val) you'll have after $this->render('file') will not reach your view.

    In CakePHP 3.x use:

    $this->viewBuilder()->template('file');
    

    Deprecated in CakePHP 3.7. Use this instead (as Kuldeep Choudhary suggested in comments)

    ViewBuilder::setTemplate('file');
    
    0 讨论(0)
  • 2021-02-01 16:48
    class StocksRealtimeController extends AppController
    {
       var $uses = 'StockRealtime';
    
       function index( )
       {
         $this->layout     = NULL;
         $this->autoRender = false;
    
         $this->set('stocksRT', $this->StockRealtime->find('all'));
    
         return $this -> render('/TestView/index');
         /*
            $this -> render('/TestView/index');
            Here 'TestView' must be a Folder named same as "public $name" variable value        
            in Controller and an "index.ctp" must be situated under TestView Folder.
           'index'
         */
       }
    }
    

    Give it a try, return 'KEYWORD' must be there to render view page successfully. Sorry about 2nd question as i didn't get it. According to CakePHP, variable [stocksTR] which is set using $this -> set( ) , also will be available at manually render view page [ 'index.ctp' ].

    0 讨论(0)
  • 2021-02-01 16:54
     $this->view  = '/TestView/index';
     $this->set('stocksRT', $this->StockRealtime->find('all'));
    
    0 讨论(0)
  • 2021-02-01 16:57
    public function admin_index() { 
    
        $this->layout = 'admin/table';
    
        $action = '/Vendors';
    
        $this->Prg->commonProcess('Vendor');
    
        $this->paginate = array('conditions' => array($this->Vendor->parseCriteria($this->passedArgs)), 'order' => 'Vendor.created_on DESC', 'limit' => 15);
    
        $this->set('vendor', $this->paginate('Vendor'));
    
        $this->render('/vendors/admin_items');
    }
    
    0 讨论(0)
  • 2021-02-01 17:02

    The right way:

    $this -> render('TestView/index');

    As the answer above mentions, you can use $this -> set to pass a variable to the View.

    However, if that doesn't give you what you want. I'm guessing that you also want the action to display another layout (non-default layout). You can try doing $this -> layout = 'layoutname'; (Layouts are in the layout folder, default on is default.ctp).

    Note: CakePHP's controller isn't designed to pass data to a non-view file (like .php). CakePHP's views should be ending with .ctp.

    0 讨论(0)
提交回复
热议问题