CakePHP: include js file in header from view

Cakephp docs say:

By default, script tags are added to the embedded document. If you override this value by setting the $ options ['inline'] parameter 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 is printed on the line, not on the head. If I miss an echo from a line in my view file, the script does not print at all in my html.

Any help would be greatly appreciated.

RAE

+5
source share
5 answers

You have false quotes, so PHP treats it as a string , 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)); 
+9
source

I would like to expand and mention a few things.

Inline script

The built-in script tag opens, which is not always needed.

 <?php echo $this->Html->script('script.name'); ?> 

Non-inline script

This will host the script where you placed $ this-> fetch ('script') in your layout file, usually at the top of the page. (As ub3rst4r pointed out, you passed false as a string)

 <?php echo $this->Html->script('script.name', array('inline' => false)); ?> 

Script block

This can be a much more useful version for many people, you can put a script block in any layout file (as much as you want). I will show you an example and call it scriptBottom to go to the end of my body.

 <?php echo $this->fetch('scriptBottom'); ?> 

You can then pass the block to a script method like

 <?php $this->Html->script('script.name', array('block' => 'scriptBottom')); ?> 

Hope this helps

+6
source

just put this in your ctp file. :)

 <?php echo $this->Html->script('//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'); ?> 
+3
source

Why do you have a lot of attributes? just use url

 echo $this->Html->script('http://code.jquery.com/jquery.min.js'); 
+1
source

In cakephp 3, instead of an array ('inline' => false), you should use an array ('block' => true) if someone is looking for an answer like me. And you don't need the script echo at the top of your ctp file, which you can just put inside php syntax, i.e.

<?php $this->Html->script('//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js', ['block' => true]); ?>

+1
source

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


All Articles