Reputation: 762
I'm using CakePHP 3.3.10. I need to add a JavaScript file to a specific view.
// default.ctp
// I need to remove this script in default.ctp and load only in a specific view.
<?= $this->Html->script(['otherfile.js', 'otherfile.js', folder/scripts.js']) ?>
How can I load the js file only in this view?:
// index.ctp
// I need to load the scripts.js file only in this view
Upvotes: 3
Views: 15099
Reputation: 29
Add css and js file on the top of view file:
echo $this->Html->script(array('ajaxupload.3.5.js'));
echo $this->Html>css(array('new_layout.css'));
Upvotes: 0
Reputation: 177
Go to your index.ctp file and insert this code at the bottom.
For JS
echo $this->Html->script('/otherdir/scripts');
or
echo $this->Html->script('http://code.jquery.com/jquery.min.js');
Will output:
<script src="http://code.jquery.com/jquery.min.js"></script>
The first parameter can be an array to include multiple files.
echo $this->Html->script(['jquery', 'wysiwyg', 'scripts']);
Will output:
<script src="/js/jquery.js"></script>
<script src="/js/wysiwyg.js"></script>
<script src="/js/scripts.js"></script>
You can append the script tag to a specific block using the block option:
echo $this->Html->script('wysiwyg', ['block' => 'scriptBottom']);
Then, in your layout, make sure to have the said block so they get outputted:
<?= $this->fetch('scriptBottom')?>
For CSS
This method of CSS inclusion assumes that the CSS file specified resides inside the webroot/css directory if path doesn’t start with a ‘/’.
echo $this->Html->css('forms');
Will output:
<link rel="stylesheet" href="/css/forms.css" />
The first parameter can be an array to include multiple files.
echo $this->Html->css(['forms', 'tables', 'menu']);
Will output:
<link rel="stylesheet" href="/css/forms.css" />
<link rel="stylesheet" href="/css/tables.css" />
<link rel="stylesheet" href="/css/menu.css" />
Upvotes: 5
Reputation: 99
<?php echo $this->Html->css('style.css',['block'=>true]); ?>
The block = true option causes the css to load inside the head tag. It will be loaded where you put the code <?php echo $ this-> fetch ('css'); ?>
in your template
Upvotes: 10
Reputation: 11
Add below code in your view :
<?php echo $this->Html->script('/otherdir/scripts'); ?>
Upvotes: 0
Reputation: 4765
Use $this->request->params['controller']
to get the current controller and $this->request->params['action']
for controller action.
Example:
<?php
// default.ctp
echo $this->Html->script(['otherfile.js', 'otherfile.js']);
if (in_array($this->request->params['action'], ['index'])){
// your conditional script block
echo $this->Html->script(['folder/scripts.js']);
}
?>
Hope it should help you to solve your problem.
Upvotes: 0