Class body类中的当前控制器和操作?

Class body类中的当前控制器和操作?,class,controller,yii2,action,Class,Controller,Yii2,Action,我需要根据当前控制器和操作更改布局样式 如何在body类中添加当前控制器和操作?您可以使用以下简单代码在body类中添加当前控制器和操作 <body class="<?php echo 'co-'.Yii::$app->controller->id. ' ac-' .Yii::$app->controller->module->requestedAction->id; ?>"> Yii方法是在控制器中定义布局:

我需要根据当前控制器和操作更改布局样式


如何在body类中添加当前控制器和操作?

您可以使用以下简单代码在body类中添加当前控制器和操作

<body class="<?php
        echo 'co-'.Yii::$app->controller->id. ' ac-' .Yii::$app->controller->module->requestedAction->id;
    ?>">
Yii方法是在控制器中定义布局:

class myControllerController extends \yii\web\Controller {
      public $layout = 'myLayout';
      // Stuff
}
// action
if (Yii::$app->controller->action->id == 'NameAction') {
  # code here 
  $this->registerCssFile("@web/..."); // Or whatever you need
}

// controller
if (Yii::$app->controller->id == 'NameController') {
  # code here ...
}
然后,为每个动作渲染不同的视图

 public function myAction() {
        [...]
        return $this->render('myaction');
 }

您可以使用以下代码获取主布局中的当前控制器和操作:

$controller = Yii::$app->controller;
$action = $controller->action->id;

<body class="<?= $controller.' '. $action ?>" >
....
</body>
$controller=Yii::$app->controller;
$action=$controller->action->id;

你可以这样做

<?php
$route = Yii::$app->controller->route;
?>
<body class="page-<?= str_replace('/', '-', $route) ?>">


您可以根据操作或控制器更改布局样式:

class myControllerController extends \yii\web\Controller {
      public $layout = 'myLayout';
      // Stuff
}
// action
if (Yii::$app->controller->action->id == 'NameAction') {
  # code here 
  $this->registerCssFile("@web/..."); // Or whatever you need
}

// controller
if (Yii::$app->controller->id == 'NameController') {
  # code here ...
}

这会改变身体等级吗?不会,但会更容易管理。如果需要,还可以将变量从控制器操作传递到视图,以设置不同的类。我的观点是,这种决策应该在控制器中进行,而不是在视图中。这不是我所问的“在身体类中添加当前控制器和操作?”谢谢:)