第一步,把你写好的js,css文件放到web目录下相应的目录中
比如我自己写了一个js文件,对应放到了basic/web/js/app.js
第二步,在basic/assets中注册,官方给我们写好了一个
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace app\assets;
use yii\web\AssetBundle;
/**
* @author Qiang Xue <[email protected]>
* @since 2.0
*/
class AppAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
'css/site.css',
];
public $js = [
'js/app.js'// 这里为自己写的js文件
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
}
资源管理已经ok了,怎么用这些资源呢?我们还是看官方给的例子
定位到basic/views/layouts/main.php文件,查看里面的源码会发现:
<?php
/* @var $this \yii\web\View */
/* @var $content string */
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use app\assets\AppAsset;
AppAsset::register($this);
?>
他的开头中有个AppAsset::register($this);
这个AppAsset就是上面第一个代码块中官方给我们写好的类了
那么我们在尝试着定义一个自己的资源管理类
第一步,在web/assets目录下新建一个类,一定要继承AssetBundle
<?php
namespace app\assets;
use yii\web\AssetBundle;
Class TestAsset extends AssetBundle {
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
'css/site.css',
];
public $js = [
'js/app.js',
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
}
第二步,想在哪个view里用这个资源,就向上面一样
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2016/7/27
* Time: 9:54
*/
\app\assets\TestAsset::register($this);
?>
注意,这里我的类名已经变成了TestAsset,这样,我们就可以方便的引入js跟css文件了
这种做法是官方比较推荐的
当然还有
$this->registerJsFile("@web/js/app.js");
$this->registerCssFile("@web/css/app.css");
这种方式,也可以引入
大家随意,我透了