Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change default view for controller in Yii2?

Tags:

php

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');
    }    
}
like image 556
Gamma Avatar asked Dec 30 '14 02:12

Gamma


2 Answers

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.

like image 183
arogachev Avatar answered Oct 16 '22 23:10

arogachev


Since 2.0.7 you can simply write in your controller's init() method: $this->viewPath = '@app/yourViewPath'

like image 2
vkabachenko Avatar answered Oct 16 '22 22:10

vkabachenko