关于Yii2 Theme 主题化的一些浅显使用笔记

1. 复制“frontend\views”目录到“frontend\themes\default”和“frontend\themes\basic”,并做一些明显的标记,也就是定义2个主题;

2. 在“SiteController.php”中添加:

public function beforeAction($action)
{
    // 使用 basic 主题
    Yii::$app->view->theme = Yii::createObject([
        'class' => 'yii\base\Theme',
        'basePath' => '@frontend/themes/basic',
        'baseUrl' => '@web/themes/basic',
        'pathMap' => [
            '@frontend/views' => '@frontend/themes/basic',
        ],
    ]);

    // 使用 default 主题
    Yii::$app->view->theme = Yii::createObject([
        'class' => 'yii\base\Theme',
        'basePath' => '@frontend/themes/default',
        'baseUrl' => '@web/themes/default',
        'pathMap' => [
            '@frontend/views' => '@frontend/themes/default',
        ],
    ]);
    return parent::beforeAction($action);
}

3. 访问“site/index”,切换两个主题,看看使用时哪个生效。


总结:给“user”表添加一个“theme”字段,定义用户使用哪个主题,然后在基本控制器中添加(代码待修改):

public function beforeAction($action)
{
    if(!Yii::$app->user->isGuest && empty(Yii::$app->user->identity->theme)){
        $theme = Yii::$app->user->identity->theme;
        Yii::$app->view->theme = Yii::createObject([
            'class' => 'yii\base\Theme',
            'basePath' => '@frontend/themes/' . $theme,
            'baseUrl' => '@web/themes/' . $theme,
            'pathMap' => [
                '@frontend/views' => '@frontend/themes/' . $theme,
            ],
        ]);
    }else{
        Yii::$app->view->theme = Yii::createObject([
            'class' => 'yii\base\Theme',
            'basePath' => '@frontend/themes/default',
            'baseUrl' => '@web/themes/default',
            'pathMap' => [
                '@frontend/views' => '@frontend/themes/default',
            ],
        ]);
    }
    return parent::beforeAction($action);
}