Yii AppAsset::register($this) 引入js和css

Yii2使用更加规范的方式,通过AppAsset::register($this)方法引入js和css文件

assets目录下有个AppAsset.php文件,内容如下:

 1 namespace backendassets;
 2 
 3 use yiiwebAssetBundle;
 4 
 5 class AppAsset extends AssetBundle
 6 {
 7     public $basePath = '@webroot';
 8     public $baseUrl = '@web';
 9     public $css = [
10         'css/site.css',
11     ];
12     public $js = [
13     ];
14     public $depends = [
15         'yiiwebYiiAsset',
16         'yiiootstrapBootstrapAsset',
17     ];
18 }

这个AppAsset类继承了YiiwebAssetBundle,它主要定义了js和css文件的路径和依赖。

在模版布局文件main.php使用AppAsset::register($this)注册这些css和js文件,除此之外,在html的head里面加上:

<?php $this->head() ?>

这句话是生成一个替换字符,表示css和js的引用代码在这里显示

原文地址:https://www.cnblogs.com/shaoing/p/5306216.html