How to change default view for controller in Yii2?

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

If we can only change the layout using public $layout, how can we do this with a view?

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

    public function actionIndex()
    {
        return $this->render('index');
    }    
}
+4
source share
2 answers

To ensure that your controller must implement ViewContextInterface .

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

class HomeController extends Controller implements ViewContextInterface

Then just add the 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 out the official documentation for organizing views.

+7
source

2.0.7 init() : $this->viewPath = '@app/yourViewPath'

+2

Source: https://habr.com/ru/post/1569374/


All Articles