Home > Article > PHP Framework > How to introduce js files in yii2
Question:
For example, I create css files and js files in the web folder, and create resource controllers in assets. So how do I call the web/css/test.css or web/js/test/js file when I am in the view layer?
The method is as follows:
1. Module reference (all pages of this module will reference it)
Yii2 uses the AssetBundle resource package class for CSS/JS management.
(Recommended tutorial: yii framework)
(Note: YII2 basic version assets/AppAsset.php, YII2 advanced version frontend/assets/AppAsset.php, here Take the basic version as an example)
namespace app\assets; use yii\web\AssetBundle; /** * @author Qiang Xue <qiang.xue@gmail.com> * @since 2.0 */ class AppAsset extends AssetBundle { public $basePath = '@webroot'; public $baseUrl = '@web'; //全局css 在这个添加css文件 public $css = [ 'css/site.css', 'css/test.css', ]; //全局js 在这里添加js文件 public $js = [ 'js/test.js', ]; //依赖关系 public $depends = [ 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapAsset', ]; }
2. To reference
in a view file, you only need to add the following code in the view file.
//引用css文件,注意自己的文件路径 <?php $this->registerCssFile('css/test.css');?> //引用js文件,注意自己的文件路径<span class="redactor-invisible-space"></span> <?php $this->registerJsFile('js/test.js');?>
If you want to learn more programming related content, please pay attention to the Programming Introduction column on the php Chinese website!
The above is the detailed content of How to introduce js files in yii2. For more information, please follow other related articles on the PHP Chinese website!