How to add css class to body tag in layout in yii2?

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

Answers (3)

Another possible solution would be using the variable $params in your view.

Example

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  ..]

Notice that

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

Yupik
Yupik

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

Olga
Olga

Reputation: 443

You add your class simply to body tag

<body class="yourClass">

Upvotes: 1

Related Questions