zen of coding

Set variable in the view to be used in the layout

I’m not sure that you should really be doing this, but I recall running into one situation where I wanted to set some variable in the view and have it available in the layout. Here’s how…

In the view:
$this->viewVars[‘myVar’] = ‘something’;

In the layout:
echo $myVar;

Nate pointed out that it can be even easier with just: $this->set(‘myVar’, ‘something’);
As $this->set(); works just as well in the view as in the controller.

Remember about MVC and double check if what you are doing is a correct approach to begin with.

  • So long as you aren’t misusing it to create controller logic in your views I don’t see a problem with technique. Thanks for posting it :-)

  • teknoid


    Yeah, I figured it’s not an MVC killer so I won’t get yelled at too much for posting this ;)

  • Actually you don’t need to use $viewVars at all. $this->set() works the same in the view as in the layout.

  • Pingback: links for 2008-06-05 « Richard@Home()

  • This could be a version difference, but I noticed the ->set doesn’t work for me. However
    I’ve found that using $this->myvar is available in layout as $this->myvar.

  • @B Lieb

    $this->set() from the view has worked for quite a while… not sure what could be the problem otherwise.

  • hey buddy. is there any way we can change the layout used according to the time of the server or clients time ?

    can u please help me.

  • check here:

    then something like…

    if($someTime) { $this->layout = ‘time_based_layout’; }

    • thanx. but how do i do this app_controller.php

  • cake

    Awesome tip for easy head update.

%d bloggers like this: