如何在 yii2 布局中将 css 类添加到 body 标签?

Саб*_*аев 2 yii2 yii2-advanced-app

我想在 frontend/views/layouts/main.php 的 yii2 advance 中将 css 类添加到 body 标签,我该怎么做?

Yup*_*pik 5

您可以像这样动态地执行此操作:

<body class="<?= $this->context->bodyClass; ?>">
Run Code Online (Sandbox Code Playgroud)

并在 main 中Controller(所有其他控制器应扩展此Controller)定义属性:

public $bodyClass;
Run Code Online (Sandbox Code Playgroud)

或默认值:

public $bodyClass = 'custom-skin';
Run Code Online (Sandbox Code Playgroud)

Ofc 您可以通过重新定义它来在任何扩展控制器中覆盖此属性:

public $bodyClass = 'custom-skin-2';
Run Code Online (Sandbox Code Playgroud)

在初始化中:

public function init() {
    parent::init();
    $this->bodyClass = 'custom-skin-2';
}
Run Code Online (Sandbox Code Playgroud)

具体动作上:

public function actionView()
{
    $this->bodyClass = 'custom-skin-3';

    return $this->render('view');
}
Run Code Online (Sandbox Code Playgroud)