- Parameters:
$url (mixed
) – Either a string to a single JavaScript file, or an
array of strings for multiple files.
$options (array
) – An array of html attributes.
Include a script file(s), contained either locally or as a remote URL.
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.
If you wish to override which block name is used, you can do so by setting
$options['block']
.
$options['once']
controls whether or not you want to include this
script once per request or more than once. This defaults to true.
You can use $options to set additional properties to the
generated script tag. If an array of script tags is used, the
attributes will be applied to all of the generated script tags.
This method of JavaScript file inclusion assumes that the
JavaScript file specified resides inside the /app/webroot/js
directory:
echo $this->Html->script('scripts');
Will output:
<script type="text/javascript" href="/js/scripts.js"></script>
You can link to files with absolute paths as well to link files
that are not in app/webroot/js
:
echo $this->Html->script('/otherdir/script_file');
You can also link to a remote URL:
echo $this->Html->script('https://code.jquery.com/jquery.min.js');
Will output:
<script type="text/javascript" href="https://code.jquery.com/jquery.min.js">
</script>
The first parameter can be an array to include multiple files.
echo $this->Html->script(array('jquery', 'wysiwyg', 'scripts'));
Will output:
<script type="text/javascript" href="/js/jquery.js"></script>
<script type="text/javascript" href="/js/wysiwyg.js"></script>
<script type="text/javascript" href="/js/scripts.js"></script>
You can append the script tag to a specific block using the block
option:
echo $this->Html->script('wysiwyg', array('block' => 'scriptBottom'));
In your layout you can output all the script tags added to ‘scriptBottom’:
echo $this->fetch('scriptBottom');
You can include script files from any loaded plugin using
plugin syntax. To include
app/Plugin/DebugKit/webroot/js/toolbar.js
you could use the following:
echo $this->Html->script('DebugKit.toolbar.js');
If you want to include a script file which shares a name with a loaded
plugin you can do the following. For example if you had a Blog
plugin,
and also wanted to include app/webroot/js/Blog.plugins.js
, you would:
echo $this->Html->script('Blog.plugins.js', array('plugin' => false));
Changed in version 2.1: The block
option was added.
Support for plugin syntax was added.