问题描述
我一直很难弄清楚如何在Yii 2
中加载jQuery
或其他CORE脚本.
I've been having a hard time trying to figure out how to load jQuery
or other CORE scripts in Yii 2
.
在Yii 1
中,似乎是这样的:
<?php Yii::app()->clientScript->registerCoreScript("jquery"); ?>
在Yii 2中,$ app是Yii的属性,而不是方法,因此上面的方法自然不起作用,而是将其更改为:
In Yii 2, $app is a property of Yii, not a method, so the above naturally doesn't work, but changing it to:
<?php Yii::$app->clientScript->registerCoreScript("jquery"); ?>
产生此错误:
Getting unknown property: yii\web\Application::clientScript
我找不到关于Yii 2的有关加载核心脚本的任何文档,因此我尝试了以下操作:
I couldn't find any documentation for Yii 2 about loading core scripts, so I tried the below:
<?php $this->registerJsFile(Yii::$app->request->baseUrl . '/js/jquery.min.js', array('position' => $this::POS_HEAD), 'jquery'); ?>
虽然这会在头上加载jQuery,但Yii也会在需要时加载第二版jQuery,因此会导致冲突错误.
Whilst this loads jQuery in the head, a second version of jQuery is also loaded by Yii when needed and hence causes conflict errors.
此外,我不想使用Yii的jQuery实现,我希望保留自己的jQuery,因此这就是我这样做的原因.
Additionally, I don't want to use Yii's implementation of jQuery, I would prefer to maintain my own and hence that is why I am doing this.
我如何在需要时不加载Yii的重复副本的情况下加载jQuery和其他核心文件?
How can I load jQuery and other core files without Yii loading duplicate copies of them when it needs them?
推荐答案
要禁用Yii2
的默认资产,您可以参考以下问题:
In order to disable Yii2
's default assets you can refer to this question:
Yii2 disable Bootstrap Js, JQuery and CSS
无论如何,Yii2
的资产管理方式与Yii 1.x.x
不同.首先,您需要创建一个AssetBundle
.作为官方指南示例,请在``:
Anyway, Yii2
's asset management way is different from Yii 1.x.x
. First you need to create an AssetBundle
. As official guide example, create an asset bundle like below in ``:
namespace app\assets\YourAssetBundleName;
use yii\web\AssetBundle;
class YourAssetBundleName extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
'path/file.css',//or files
];
public $js=[
'path/file.js' //or files
];
//if this asset depends on other assets you may populate below array
public $depends = [
];
}
然后,将其发布到您的视图中:
Then, to publish them on your views:
use app\assets\YourAssetBundleName;
YourAssetBundleName::register($this);
$this
引用当前视图对象.
另一方面,如果您只需要将JS
文件注册到视图中,则可以使用:
On the other hand, if you need to only register JS
files into a view, you may use:
$this->registerJsFile('path/to/file.js');
yii \ web \ View :: registerJsFile()
如果只需要将CSS
文件注册到视图中,则可以使用:
And if you need to only register CSS
files into a view, you may use:
$this->registerCssFile('path/to/file.css');
yii \ web \ View :: registerCssFile()
这篇关于在Yii 2中加载jQuery之类的核心脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!