CakePHP how to addScript () from inside element?

I have a navigation menu inside the CakePHP file element(views / elements / nav_default.ctp).

The file is included inside another element, which is the header (views / elements / header_default.ctp), which is then included in the layout file (views / layouts / default.ctp).

I'm trying to tell Cake to load the js file (webroot / js / mega_drop.js) from the nav element like this:

<?php
$this->addScript('mega_drop');
?>

It does not turn on. I looked at the documentation for addScript , which simply says:

Adds content to internal scripts buffer. This buffer is available in the layout as $ scripts_for_layout. This method is useful when creating helpers that need to add javascript or css directly to the layout. Keeping that scripts added from the layout or elements in the layout will not be added to $ scripts_for_layout. This method is most often used from within helpers such as Javascript and Html Helpers.

The key part:

Keep in mind that scripts added from the layout or elements in the layout will not be added to $ scripts_for_layout.

So how do I do this?

I think I could add <script src="/js/mega_drop.js"></script>to the layout default.ctp. This does not seem to be correct, because since it will closely link the layout and element together.

What is the best CakePHP best practice for this?

+3
3

addScript() ; $scripts_for_layout. , , JavaScript . - - . , , JavaScript , , .

script HTML Helper- echo $this->Html->script("script or array('of', 'scripts')"); , $this->set('scripts', 'mega_drop'); , Html Helper $scripts .

: , nav_default.ctp . $this- > set() ( , view), . , viewVars . , , () if(isset($scripts)) { echo $this->Html->script($scripts); } .

+4

1.3.x CakePHP 2.0 Dev example.ctp:

$this->addScript($this->Javascript->link('tab_enabler')); 
$this->addScript($this->Html->css('jquery.tabs'));

, CSS JS $scripts_for_layout, W3C, css <BODY></BODY>

+3

$this->Html->script('mega_drop', $inline=false);

.

, $scripts_for_layout.

You should be able to do this in your element so that javascript is included only when that element.

+1
source

Source: https://habr.com/ru/post/1785976/


All Articles