0

I have a project where the user chooses the layout, and saves it in the database, how do I choose to change this layout in real time?

For example; http://www.example.com/username/controller/action/id

Throughout the site I would have with the first parameter the username, which is actually where the system will know which layout it chose.

Can anybody help me?

EDITED

For example; When the user accesses the site I pass the following link: www.example.com/index.php?layout=4545455, so I would be able to know which layout to use, but how do I keep this parameter layout=4545455 on all routes Site? Well if I click on the about menu it will be with the url www.example.com/index.php?r=site/about

4

3 回答 3

2

您可以在登录控制器中设置布局。当用户登录成功时,从数据库中获取他的布局并将布局设置为$this->layout = "layout_name". 前提是您需要在视图文件夹中准备好布局文件

注意:请参阅@sm1979 的答案以获取更多详细信息

于 2016-11-21T05:19:00.533 回答
1

您提到用户选择的布局存储在数据库中。您可以在登录后立即使用该信息并覆盖应用程序组件中的默认布局。

登录操作的代码片段可能是这样的:

....
if ($model->load(Yii::$app->request->post()) && $model->login()) {
    //you can use Yii::$app->user->id and get the corresponding layout info
    //using something like below, assuming UserLayouts as the model
    //corresponding to the table storing user's layout choice  
    $layout = UserLayouts::find()->where(['user_id' => Yii::$app->user->id])->one();

    Yii::$app->layout = $layout->id; //you should fetch the field which is the name of the layout file

    //redirect to landing page for member
    ...
}

这将为该特定会话的所有控制器设置特定用户的布局,因此您不必在 URL 中传递布局信息。请注意,仅当您不覆盖每个控制器中的布局属性时,此方法才有效。

这也是 Nitin P 的建议。唯一的区别是他建议 set $this->layout = "layout_name",我相信它将仅为该特定控制器而不是所有控制器设置布局。来自 Yii2 指南(http://www.yiiframework.com/doc-2.0/guide-structure-views.html#using-layouts):

yii\base\Application::$layout您可以通过配置或来使用不同的布局yii\base\Controller::$layout。前者管理所有控制器使用的布局,而后者覆盖了单个控制器的前者。

我没有足够的声誉来评论他的答案,所以我添加了新的答案。

于 2016-11-22T11:24:28.033 回答
0

在所有人的帮助下,我得到了以下信息:

class MainController extends \yii\base\Controller {

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

    public function beforeAction($action) { 
        if(Yii::$app->request->get('layout')) {
            $this->layout = 'set_layout';
        }

        return parent::beforeAction($action);
    }
 } 


class SiteController extends MainController
{
  // code here 
}

我创建了一个主控制器,我创建的所有控件都将继承自它。并且使用该beforeAction ($ action)方法我可以根据 url 中的内容更改布局。(例如 www.example.com/index.php?layout=485121)

于 2016-11-22T15:51:14.380 回答