Answer the question
In order to leave comments, you need to log in
How to create multiple themes in yii2?
Hello.
Faced the problem of creating multiple themes, now in the config:
'components'=>[
'view' => [
'theme' => [
'basePath' => '@app/themes/theme1',
'baseUrl' => '@app/themes/theme1/web',
'pathMap' => [
'@app/views' => '@app/themes/theme1/views',
],
],
],
],
Answer the question
In order to leave comments, you need to log in
Good afternoon.
Once, too, was interested in this topic. There are several options for solving the problem.
For example, in SiteController you can do this:
public function init()
{
parent::init();
// Вариант 1
// Работает без компонента в конфигурации
// 'view' => [
// 'theme' => []
// ]
$theme = Yii::$app->request->get('theme');
if($theme){
$this->getView()->theme = Yii::createObject([
'class' => '\yii\base\Theme',
'baseUrl' => '@web/themes/'.$theme,
'basePath' => '@app/themes/'.$theme,
'pathMap' => ['@app/views' => '@app/themes/'.$theme],
]);
}
// Вариант 2
//Работает, если в конфигурации есть компонент без параметров
// 'view' => [
// 'theme' => []
// ]
Yii::$app->view->theme->basePath = '@app/themes/admin';
Yii::$app->view->theme->baseUrl = '@web/themes/admin';
Yii::$app->view->theme->pathMap = ['@app/views' => '@app/themes/admin'];
}
// Вариант 3
// устанавливает тему на лету
// вид ссылки
// <a href="themeswitch/theme=theme_name">theme_name</a>
//
public function actionThemeswitch($theme)
{
if($theme == 'default'){
Yii::$app->response->cookies->remove('theme');
return $this->redirect(['index']);
}
$options = ['name'=>'theme','value'=>$theme,'expire'=>time()+86400*365];
$cookie = new \yii\web\Cookie($options);
Yii::$app->response->cookies->add($cookie);
return $this->redirect(['index']);
}
public function beforeAction($action)
{
if (parent::beforeAction($action)) {
if (Yii::$app->request->cookies['theme']) {
$theme = Yii::$app->request->cookies->getValue('theme');
Yii::$app->view->theme = new \yii\base\Theme([
'pathMap' => ['@app/views' => '@app/themes/'.$theme],
'baseUrl' => '@web',
]);
}
return true; // or false if needed
} else {
return false;
}
}
use app\assets\PortfolioAsset;
$image = PortfolioAsset::register($this);
$theme = $this->theme;
echo Html::img($image->baseUrl.'/img/portfolio-1.jpg',
['alt' => '']);
public $sourcePath = '@app/themes/portfolio/assets';
As an option:
'view' => [
'theme' => require(__DIR__ . '/theme.php'),
]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question