Rendering controller to a different view in CakePHP

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.


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

$this->render('file');

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

Tags:

Php

Cakephp