2014-11-14 136 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的解决方案就足够了。