Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP: Include js file in header from view

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

like image 984
Peter Avatar asked Oct 22 '14 21:10

Peter


4 Answers

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));
like image 114
ub3rst4r Avatar answered Sep 27 '22 19:09

ub3rst4r


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

like image 40
HelloSpeakman Avatar answered Sep 27 '22 20:09

HelloSpeakman


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'); ?>
like image 34
r3mmel Avatar answered Sep 27 '22 21:09

r3mmel


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]); ?>

like image 39
Battousai Avatar answered Sep 27 '22 19:09

Battousai