我正在使用CakePHP 3.3.10。我需要将JavaScript文件添加到特定视图。
// 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']) ?>
如何仅在此视图中加载js文件?:
// index.ctp
// I need to load the scripts.js file only in this view
答案 0 :(得分:5)
转到index.ctp文件并在底部插入此代码。
对于JS
echo $this->Html->script('/otherdir/scripts');
或
echo $this->Html->script('http://code.jquery.com/jquery.min.js');
将输出:
<script src="http://code.jquery.com/jquery.min.js"></script>
第一个参数可以是包含多个文件的数组。
echo $this->Html->script(['jquery', 'wysiwyg', 'scripts']);
将输出:
<script src="/js/jquery.js"></script>
<script src="/js/wysiwyg.js"></script>
<script src="/js/scripts.js"></script>
您可以使用块选项将脚本标记附加到特定块:
echo $this->Html->script('wysiwyg', ['block' => 'scriptBottom']);
然后,在您的布局中,确保拥有所述块以便输出:
<?= $this->fetch('scriptBottom')?>
适用于CSS
这种CSS包含方法假定指定的CSS文件驻留在webroot / css目录中,如果路径不以'/'开头。
echo $this->Html->css('forms');
将输出:
<link rel="stylesheet" href="/css/forms.css" />
第一个参数可以是包含多个文件的数组。
echo $this->Html->css(['forms', 'tables', 'menu']);
将输出:
<link rel="stylesheet" href="/css/forms.css" />
<link rel="stylesheet" href="/css/tables.css" />
<link rel="stylesheet" href="/css/menu.css" />
答案 1 :(得分:0)
使用$this->request->params['controller']
获取当前控制器,使用$this->request->params['action']
进行控制器操作。
示例:
<?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']);
}
?>
希望它可以帮助您解决问题。
答案 2 :(得分:0)
在视图中添加以下代码:
<?php echo $this->Html->script('/otherdir/scripts'); ?>
答案 3 :(得分:0)
在视图文件的顶部添加css和js文件:
echo $this->Html->script(array('ajaxupload.3.5.js'));
echo $this->Html>css(array('new_layout.css'));