Php 动态设置视图对象的主题数组时出现问题
我在Php 动态设置视图对象的主题数组时出现问题,php,yii,yii2,Php,Yii,Yii2,我在Yii2中使用,之前是通过应用程序配置文件这样做的: 'view' => [ 'theme' => [ 'pathMap' => [ '@app/views' => [ '@app/themes/test', '@app/themes/default', ], ], 'baseUrl' => '@
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');
请注意,当直接而不是通过视图实例设置
basePath
和baseUrl
属性时,需要使用getAlias()
,以便传入正确的路径/url;然而,pathMap
声明您可以在其中使用别名。也许新配置中的path\u map
应该是pathMap
像旧配置一样?@bishop我不太明白您的意思?您的自定义文件有这行$theme\u data['path\u map']
。您的旧配置具有'theme'=>['pathMap'=>[…]]
。这些键不匹配:path\u map
!=<代码>路径图。也许他们应该。哦。。。。我懂了。我改了,但还是有同样的错误。我将使用getAlias()
@bishop Nope重试,即使在使用getAlias()
更改并重试后,也会出现相同的错误。