Passing Parameters Into Your Layouts in CakePHP

tags: php · 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.

Tunny
Fri, May 30th 2008, 04:21

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 :)

joex
Tue, Dec 9th 2008, 16:17

thank you, i'll use this technique, and the idea given grom Tunny, bye!

greeting from chile!

Grover Campos
Sat, Dec 20th 2008, 11:07

Great post, nice, thanks

Ricardo Pandales
Sun, Dec 21st 2008, 11:38

THANKSSSSSS :)

Add A Comment

Some html formatting accepted. Please use Markdown syntax for entering formatting markup. All comments are moderated and we reserve the right to remove inappropriate material.