简体   繁体   中英

CakePHP: $this->Html->script doesn't work inside element when applied to layout

I'm using CakePHP 2.x

I have a couple elements that require javascript files, so inside the element ctp file ( whatever.ctp ) I do something like this: $this->Html->script('whatever.js', array('inline'=>false)); This normally works great...

But I noticed that when I try to use this exact same element directly on a layout (not a view) it doesn't work:

//inside default.ctp layout echo $this->element('whatever');

The element shows up normally, but the scripts do not get added to the script block. If I move that same element into a view, the scripts do get added. Or if I take the scripts out of the element and just add $this->Html->script('whatever.js', array('inline'=>false)); to the default. That also works.

So why can't elements add to the script block outside of a view?

In case it's not clear...

//this works
layout -> view -> element -> $this->Html->script()

//this works
layout -> $this->Html->script()            

//this DOESN'T work
layout -> element -> $this->Html->script()

It does ALL work as long as you didnt output the scripts yet. You need to understand the execution order. Views first, then layout. Once the layout renders, and once you output the buffered content, you cannot use buffered output anymore (using inline false). You would THEN need inline true and directly echo it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM