sam
sam

Reputation: 956

how to pass values from controller to layout file in yii2

I'm trying to pass a variable value from controller to my main.php layout file but i keep getting error Undefined variable: contentWrapperBackground. below is my code

controller
public function actionList()
{

   $contentWrapperBackground = "ff4400;";
    $contentBackground = "3c8dbc;";
    return $this->render('list', [

         'contentWrapperBackground' =>$contentWrapperBackground,
         'contentBackground' => $contentBackground,

    ]);
}

and in my layout file like this

<div class="content-wrapper" style="background-color:#<?=$contentWrapperBackground?>">
    <!-- Content Header (Page header) -->


    <!-- Main content -->
    <section class="content" style="background-color:#<?=$contentBackground?>">

but i always get error Undefined variable: contentWrapperBackground. I'm trying to change the background color of for different pages. any help on this, and am also open to another idea on how to make this work thanks

Upvotes: 0

Views: 2996

Answers (2)

Mohsen
Mohsen

Reputation: 1422

you can set param in controller

Yii::$app->view->params['paramName'] = 'data';

get data in layout

$this->params['paramName'];

Upvotes: 1

Amigo Nikola
Amigo Nikola

Reputation: 46

don't use session for this!

Simple solution:

class Controller extends \yii\web\Controller
{
    $public $contentWrapperBackground;

    $public $contentBackground;
}

class YourController extends Controller
{
    public function actionList()
    {

         $this->contentWrapperBackground = "ff4400;";
         $this->contentBackground = "3c8dbc;";
         return $this->render('list', []);
    }
}

in your main layout

<div class="content-wrapper" style="background-color:#<?=Yii::$app->controller->contentWrapperBackground?>">

or another option

<div class="content-wrapper" style="background-color:#<?=$this->context->contentWrapperBackground?>">

Upvotes: 2

Related Questions