Layout With Dynamic Variable Inside

Hello, community!

I’ve just started learning Yii, I am new with MVC and I got a question that I hope you will help to answer.

The question is the following.

I have a layout for my website, where I store the header, footer, main site menu and another static stuff.

In my layout in the <head></head> section I have my .css / .js files, which are used on every page. It’s fine. But I have several color representations of my layout. These representations of template are equal (equal structure, equal elements etc.) the only difference is colors of elements (I have different colors of design: blue, green, red etc.). So for each version of design I got my own .css file.

The problem is to include into layout the correct .css file depending on which color version of template is used currently (color version of template is storing in the $_SESSION array).

It’s like:

If $_SESSION["tpl"] is "red", I need to include tpl_red.css. If $_SESSION["tpl"] is "blue", I need to include tpl_blue.css etc…

In my layout I have the following peace of code:


...

<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/<?php echo $theme_file; ?>" />

...

From where I can check the current version of design to assign to my layout the name of correct .css file. It looks very uncomfortable to do it in all the controllers of my site. Is there any global place, where I can do it once? Or, maybe there is another way to solve my problem?

Hi Doojin and welcome to Yii community!

Yes you could do it in components/Controller.php


  public function init() {

        parent::init();

       //check and set anything you want!

  }

Any yourController that extends the Controller runs firstly the init method, so before an action runs (and view or layout-template ofcourse!) you could check almost anything! :)

Best regards

Oh. Of course… The "init()" method. I completely forgot about it.

Thank you very much. That’s what I need.