Loading core scripts such as jQuery in Yii 2

后端 未结 2 442
误落风尘
误落风尘 2021-02-09 15:58

I\'ve been having a hard time trying to figure out how to load jQuery or other CORE scripts in Yii 2.

In Yii 1 it seemed this was

相关标签:
2条回答
  • 2021-02-09 16:43

    You can remove the core jQuery from loading like so:

    config/web.php

    'assetManager' => [
        'bundles' => [
            // you can override AssetBundle configs here       
             'yii\web\JqueryAsset' => [
                'sourcePath' => null,
                'js' => [] 
            ],        
        ],
    ],
    
    0 讨论(0)
  • 2021-02-09 16:48

    In order to disable Yii2's default assets you can refer to this question:

    Yii2 disable Bootstrap Js, JQuery and CSS

    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);
    

    Which $this refers to current view object.


    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()

    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()

    0 讨论(0)
提交回复
热议问题