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.
Since 2.0.7 you can simply write in your controller's init() method: $this->viewPath = '@app/yourViewPath'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With