tags:

views:

269

answers:

2

Hi I'd like to set the layout's $scripts_for_layout from within the controller. Is this possible, and if yes how?

+1  A: 

Short answer: maybe you're doing it wrong.

Long answer: Scripts should not be controller dependent. It's 'theoretically' wrong, and cake does not like people who doesn't adhere to the mvc pattern.

Workaround (because sometimes you just need to): You can set in beforeRender a var:

function beforeRender() {
    parent::beforeRender();
    $this->set('scripts', array('script1', 'script2' ...));
}

And in the layout check for $scripts and add them.

Enrico Carlesso
Now that you're saying it, I understand that I'm doing it wrong. I didn't want the scripts in every view, and I thought it would be cleverer to use the controller file. So I only have one file to edit.
kaklon
Maybe you can use different layout, if it's better for you. In the years I find out that every thing I was trying to do that cake wont let me was just wrong, or not MVC-compliant.Cake is wonderful also because force you to write well, clean and structured code.
Enrico Carlesso
+1  A: 

In cake 1.2, when you do $this->set('script_for_layout', 'script here...), it will convert this variable to $scriptForLayout so it wouldn't work.

Cake 1.3 fixed this but I haven't tried to see if it works or not but you are violating MVC because script was meant for the View, not set at the Controller level. For dynamic script, you can assign variables to your view like the previous poster has suggested.

KienPham.com