Yii2 How to add external css and javascrip files to the Yii application

Yii2 How to add external css and javascrip files to the Yii application

  • 08 Sep 2016
  • 10

Adding css and javascrip files to the yii application isn't as straight forward as typing the style and scrip tags.

There are few steps you need to follow. Yii2 has asset management. The css and the javascript files are asset files. So to add them to the yii application you should edit the AppAsset.php file in the assets directory

Below is how the AppAsset.php file looks like

class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/site.css',
        ];
    public $js = [


    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
    ];
}

If you check the web directory you must have noticed the css folder store your external css file there

and change the public $css array as follows



public $css = [
        'css/site.css',
        'css/externalCssFile.css'
        ];


Its also best to create a js folder in the web directory to store your javascript files. Next change the public $js array as follows

public $js = [
     'js/externalJsFile.js',
    ];


Now these two files will be applied to the whole of the Yii application if you want to add a separate files for separate views then you will have to create a separate asset.php file for those views like the layoutMainAsset.php file that I have created ( Check Out my Youtube Channel For Yii2 Tutorials ) for the layouts/main.php file

Okay that's it for this lesson see you around next time. Have fun Yii developers