CakePHP: Include js file in header from view
Solution 1
You have false
in quotes, so PHP is treating it as a string
and not a boolean
. It should be:
echo $this->Html->script('//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js', array('inline' => false));
Solution 2
I'd want to expand and mention a couple of things on this.
Inline Script
This will print out the script tag inline which isn't always desired.
<?php echo $this->Html->script('script.name'); ?>
Non-Inline Script
This will place the script where ever you placed $this->fetch('script') in your layout file, usually in the head of your page. (As pointed out by ub3rst4r you were passing false as a string)
<?php echo $this->Html->script('script.name', array('inline' => false)); ?>
Block Script
This might be a much more useful version for many people, you can place a script block in any layout file (as many as you wish actually). I'll show you an example and call it scriptBottom to go before the end of my body.
<?php echo $this->fetch('scriptBottom'); ?>
Then you can pass the block to the script method like such
<?php $this->Html->script('script.name', array('block' => 'scriptBottom')); ?>
Hope this helps
Solution 3
just put this in your view ctp file. :)
<?php echo $this->Html->script('//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'); ?>
Solution 4
In cakephp 3 instead of array('inline' => false) you should use array('block' => true) if anyone is looking for that answer like I was. And you don't need to echo the script at the top of your ctp file you can just place inside php syntax i.e.
<?php $this->Html->script('//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js', ['block' => true]); ?>
Solution 5
Why are u going on lot of attributes ?? simply use url
echo $this->Html->script('http://code.jquery.com/jquery.min.js');
Peter
Updated on June 26, 2022Comments
-
Peter almost 2 years
The cakephp docs say:
By default, script tags are added to the document inline. If you override this by setting $options['inline'] to false, the script tags will instead be added to the script block which you can print elsewhere in the document.
So in my view file (.ctp) I have:
echo $this->Html->script('//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js', array('inline' => 'false'));
And in my layout, in the head tag:
echo $this->fetch('script');
But the script tag prints out inline and not in the head. If I miss of the echo from the line in my view file, the script doesn't print out at all in my html.
Any help would be gratefully received.
PAE