5

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

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. yii\base\Controller already implements the interface, so the implements ViewContextInterface is redundant here.
2

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

Comments

1

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.