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

时间:2015-08-17 13:47:27

标签: php yii yii2

我在Yii2中使用theming,之前通过应用程序配置文件执行此操作:

'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()与这些设置一起使用,但却遇到了同样的错误。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

好的,这就是我的所作所为:

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表示您可以在其中使用别名。