Reputation: 2196
I've just started using cakephp elements and they're awesome (I used to use include).
I have an element gallery and an element called comments (for a certain page) and for them I have some javascript code attached to both of them. Do you have any suggestions on how I could include that javascript code in the element? If I simply add it like that it will load javascript before loading the html after the element and I don't think it's very wise.
Upvotes: 1
Views: 5644
Reputation: 513
In cakephp 3 instead of array('inline' => false)
you should use array('block' => true)
if anyone is looking for that answer like I was.
Upvotes: 2
Reputation: 2712
If I understand you correctly, you want to have JS specific to a page loading in the header when you call a certain element, but that the JS could be different for each element. You also want the JS to be referenced at the beginning of your HTML document.
This is actually quite easy to do. Just make sure that you have <?php echo $scripts_for_layout; ?>
in you <head>
tag in the layout you are using.
Then, within the element, just do:
<?php $this->Html->script("js_file", array("inline"=>false)); ?>
js_file is the name of your JavaScript file in app/webroot/js/. In this case, the file would be called js_file.js but you must leave off the .js when referencing it as above.
It doesn't matter where abouts in the element file you put this because the "inline"=>false
part ensures it won't actually appear at that stage in the code. Instead, it will appear in the <head>
wherever you put <?php echo $scripts_for_layout; ?>
in your layout.
Upvotes: 3
Reputation:
You could put the Javascript code directly into the element file, or put the Javascript code in into your webroot folder, <cake directory>/app/webroot/js/
and include the file in your layout by using the HTML helper:
echo $html->script("myCode");
If you're worried about the Javascript code executing before the page has completely loaded, then use window.onload or $(document).ready() if you're using JQuery.
Upvotes: 6