Gamma Gamma - 8 months ago 72
PHP Question

How to change default view for controller in Yii2?

I was wondering can I change default view folder for a controller in Yii2?

If we can change layout just by using

public $layout
, how we can do it with view?

Class HomeController extends \yii\web\Controller
public $layout = 'mylayout';
public $view = 'newview';

public function actionIndex()
return $this->render('index');


To achieve that your controller should implement ViewContextInterface.

use yii\base\ViewContextInterface;
use yii\web\Controller;

class HomeController extends Controller implements ViewContextInterface

Then just add getViewPath() method which should return the desired directory path:

public function getViewPath()
    return Yii::getAlias('@frontend/views/newview');

You can use aliases here.

Also check the official documentation about organizing views.