Passing Parameters Into Your Layouts in CakePHP
One problem I recently stumbled upon while developing a site with CakePHP is the issue of controlling elements in a layout. For instance, in one of my controllers, I want to be able to change the look of an element I have embedded in my layout (in this case, it was a simple menu item, that changes depending on what part of the site is being accessed). How can I change this element if it is in the layout, and I have no direct means of communication between my various controllers and the layout?
Interestingly enough, the developers over at CakePHP incorporated this little interesting tidbit: any variable set for your view with a name ending in “_for_layout” automatically gets passed into the layout.
Here’s a little example:
//in my controller
$this->set(‘var_for_layout’,$value);
//here is the code in my layout, to pass the value I set in
//my controller to a javascript var
echo $javascript->codeBlock(‘var mainmenu = “’ . $var_for_layout . ‘”;’);
I've used this technique for several different problems I've encountered while working in cakephp. For instance, I wanted to be able to set the meta description tag on each page with my own custom value. That was easy enough by simply using a description_for_layout variable which I set in my PostsController after fetching the corresponding post.
That’s something I would have liked to see in the documentation.
Here is an implementation of a helper for more fine-grained control of layout elements.
Nice post. Knowing that's made my life much simpler.
I used to override app_controller and before render and pass variables to the layout. Glad I don't have to do that any more :)
thank you, i'll use this technique, and the idea given grom Tunny, bye!
greeting from chile!
Great post, nice, thanks
THANKSSSSSS :)