简体   繁体   中英

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.

从 2.0.7 开始,您可以简单地在控制器的 init() 方法中编写: $this->viewPath = '@app/yourViewPath'

I'm on Yii 2.0.42.1, And added this in my controller.

public function init()
{
     $this->viewPath = '@app/modules/report/views/test';

      parent::init();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM