2014-11-14 130 views
0

如何動態設置主題?我在用戶配置文件中有一個允許選擇主題的字段。我在@webroot和不同的主題中創建了一個主題文件夾。Yii2動態主題

當用戶正在查看他的個人資料時,我需要設置他已選擇或設置爲默認主題的主題。

回答

0

如果你想改變的主題動態,你可以做這樣的事情。

功能切換主題:

public function actionThemeswitch($theme) 
{ 
    $options = ['name'=>'theme','value'=>$theme,'expire'=>time()+86400*365]; 
    $cookie = new \yii\web\Cookie($options); 
    Yii::$app->response->cookies->add($cookie); 

    return $this->redirect(['backend/info']); 
} 

創建自定義控制器和擴展了下面所有的控制器:

<?php 
namespace frontend\components; 

class Controller extends \yii\web\Controller { 
    public function beforeAction($action) 
    { 
     if (parent::beforeAction($action)) { 
      $theme = "blue"; 
      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; 
     } 
    } 
} 
+0

它不適用於模塊 – user1954544 2017-02-26 10:42:48

0

在控制器\抽象控制器(我用抽象控制器所有控制器) 。我也在先進的Yii2中做到這一點,但不要認爲有問題...只需更改你需要的別名。

public function init() 
    { 
     parent::init(); 

     \Yii::$app->setLayoutPath('@backend/views/theme_'.$this->getView()->themeName.'/layouts'); 
     $this->setViewPath($this->module->getViewPath().'/theme_'.$this->getView()->themeName.'/'.$this->id); 
    } 

$this->getView()->themeName是一個字符串,在我的情況下,它在擴展視圖類,但你可以加載\保存它,你喜歡什麼都...(負載從配置文件)

後,在模塊和基礎的應用程序,你應該這樣創建視圖:

... 
--views 
----theme_b3 
------controller1 
--------action1 
----------index.php 
----------add.php 
----------remove.php 

----theme_adminLTE 
------controller1 
--------action1 
----------index.php 
----------add.php 
----------remove.php 

主要的一點是要與theme_ {THEMENAME}(「B3」,「adminLTE」)創建文件夾並存儲在那裏所有佈局\我們需要的觀點,但在舊位置。

因此,您不需要在根目錄下創建「主題」文件夾,所有視圖將位於相同的位置,但位於子文件夾中。

順便說一句,在這種情況下,我們可以輕鬆地通過cookie或配置,從舊主題更改爲新的主題。

PS:如果你使用了很多模塊,這個解決方案是很好的。在基本應用程序中,來自@Ravindra Bhalothia的解決方案就足夠了。