Yii2: How to dynamically switch theme

Created on 16 Jun 2014  路  8Comments  路  Source: yiisoft/yii2

i try to do this, it's not work
\Yii::$app->view->theme = '@app/themes/blue';

Most helpful comment

Currently written in such a way, if there is nothing wrong?

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']);
}

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;
    }
}

@samdark

All 8 comments

where do you do it in your code?

I want to implement click a link to switch themes

public function actionThemeswitch($theme)
{
        \Yii::$app->view->theme = $theme;
        return $this->refresh();
 }

@cebe

The mistake is the fact that PHP application "dies" every request so each config option you're setting runtime is valid only on current request. You need to store it somewhere (session, cookies etc.) and re-initialize it like you did on each application start.

Currently written in such a way, if there is nothing wrong?

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']);
}

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;
    }
}

@samdark

Yes, looks OK.

And for assetsBundle? How change it on the fly? In addition to the theme usually also the resources to be included (css, js, etc ....)

Was this page helpful?
0 / 5 - 0 ratings