动态设置视图对象主题数组的问题


Problems setting theme array of view object dynamically

我在Yii2中使用主题化,以前是通过应用程序配置文件这样做的:

'view' => [
    'theme' => [
        'pathMap' => [
            '@app/views' => [
                '@app/themes/test',
                '@app/themes/default',
            ],
        ],
        'baseUrl' => '@web/themes/default',
        'basePath' => '@webroot/themes/default',
    ],
],

这个工作正常;然而,我需要改变事情,动态地做,所以我尝试在一个自定义文件中运行下面的代码在引导过程中:

// Set our current theme
$theme_data['pathMap']['@app/views'][] = '@app/themes/' . Yii::$app->params['settings']['selected_theme'];
// Do we need to add our default theme as a fallback?
if (Yii::$app->params['settings']['selected_theme'] != 'default') {
    $theme_data['pathMap']['@app/views'][] = '@app/themes/default';
}
// Set our base url and base path keys
$theme_data['baseUrl'] = '@web/themes/default';
$theme_data['basePath'] = '@webroot/themes/default';
// Now set the data in our view instance
Yii::$app->view->theme = $theme_data;

由于应用程序配置中的设置,该文件在上面指定的引导过程中运行:

'bootstrap' => [
                //....
                'app'base'Settings',
],

但是现在当我尝试加载网站时,我得到错误:

Call to a member function applyTo() on a non-object

…这似乎是由渲染视图文件的调用引起的。

我甚至尝试使用Yii::getAlias()与这些设置,但得到相同的错误。

我在这里做错了什么?

好的,我是这样做的:

use yii'base'Theme;
// Set our view theme property to a theme instance
Yii::$app->view->theme = new Theme();
// Set our current theme
$path_map['@app/views'][] = '@app/themes/' . Yii::$app->params['settings']['selected_theme'];
// Do we need to add our default theme as a fallback?
if (Yii::$app->params['settings']['selected_theme'] != 'default') {
    $path_map['@app/views'][] = '@app/themes/default';
}
// Update our path map
Yii::$app->view->theme->pathMap = $path_map;
// Set our base url and base path keys
Yii::$app->view->theme->baseUrl = Yii::getAlias('@web/themes/default');
Yii::$app->view->theme->basePath = Yii::getAlias('@webroot/themes/default');

请注意,当设置basePathbaseUrl属性直接和不是通过视图实例,你需要使用getAlias(),所以你在正确的路径/url;而pathMap规定你可以在里面使用别名