How to change default view path in Yii2?

╄→尐↘猪︶ㄣ 提交于 2019-12-10 15:43:46

问题


I am trying to do multi theme in advanced-yii2. I tried a lot of way for this but it doesn't work I can't understand. Firstly, I added this to "frontend/config/main.php";

          'view' => [
              'theme' => [
                 'pathMap' => [ 
                    '@app/views' => [ 
                        '@webroot/themes/demo/views',

                     ]
                 ],
               ],
            ],

and it doesn't work, then I tried to creating a new view class for frontend, for example:

    namespace frontend\components;

class NewsView extends \yii\web\View {

    function init() {
    \Yii::$app->view->viewPath = '@webroot/themes';
    parent::init();
    }

}

and added in config.php

'view' => [
        'class' => 'frontend\components\NewsView',

but it doesn't work too.

What should I do?


回答1:


You can redefine getViewPath method at your base controller. Like

public function getViewPath()
{
    return Yii::getAlias('@frontend/views/newview');
}



回答2:


In a controller you can change the view path also in the init method:

public function init() {
    parent::init();
    $this->viewPath = '@frontend/views/newview'; // or before init()
}

Or use the already suggested way.


Hint for idiots like me: Don't try to override the $viewPath property.

class MyController extends Controller {
    public $viewPath = '@frontend/views/newview'; // Doesn't work
}

This won't work. Actually the private member $_viewPath needs to be set in the base controller! It will be evaluated on rendering (if parameter $view is a relative path). $this->viewPath = '...'; calls a setter function which sets $_viewPath. If you override $viewPath with public $viewPath = '...'; calling the magic setter function is not possible anymore, thus $_viewPath will not be changed.



来源:https://stackoverflow.com/questions/27028712/how-to-change-default-view-path-in-yii2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!