[yii2.0 中文手册]yii2.0模板引用js与css文件

更新时间:2019-11-08    来源:php函数    手机版     字体:

【www.bbyears.com--php函数】

Yii2使用更加规范的方式,通过AppAsset::register($this)方法引入js和css文件,在Yii2的示例中,layouts的main.php中就有它的用法:AppAsset::register($this)。


在WEB目录中,会有一个assets目录,这个目录下有个Appasset.php文件,内容如下:

namespace frontend\assets;
 
use yii\web\AssetBundle;
 
/**
 * @author Qiang Xue
 * @since 2.0
 */
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",
    ];
}

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

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

head() ?>

这句话是生成一个替换字符,表示css和js的引用代码在这里显示。别忘了在head里加上这句。

本文来源:http://www.bbyears.com/jiaocheng/77915.html