问题
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