Reputation: 80
I want to add css class to body tag in yii2 advanced in frontend/views/layouts/main.php how can I do it?
Upvotes: 2
Views: 3005
Reputation: 21
Another possible solution would be using the variable $params
in your view.
In your view you can define:
$this->params['bodyClass'] = 'yourclass';
And then, in your layout file, you'd go:
[.. head and other codes ..]
<body <? if(isset($this->params['bodyClass'])) echo 'class="' . $this->params['bodyClass'] . '"'; ?>>
<?php $this->beginBody() ?>
[.. rest of your code ..]
I'm suggesting you to use the if so it only puts the class if it the $params['bodyClass'] is set in your view.
Also, you can use whatever name you want in the place of bodyClass.
This example will output <body class="yourclass">
Cheers.
Upvotes: 1
Reputation: 5032
You can do this dynamically like this:
<body class="<?= $this->context->bodyClass; ?>">
And in main Controller
(all other controllers should extend this Controller
) define property:
public $bodyClass;
or for default value:
public $bodyClass = 'custom-skin';
Ofc you can override this property in any extending controller by redefining it:
public $bodyClass = 'custom-skin-2';
In init:
public function init() {
parent::init();
$this->bodyClass = 'custom-skin-2';
}
In specific action:
public function actionView()
{
$this->bodyClass = 'custom-skin-3';
return $this->render('view');
}
Upvotes: 5