yii2怎么引入css和js文件

yii2怎么引入css和js文件

引入方式有多种:

1、可以直接在视图页面上引入

<?php  use YIIhelpersHtml;?>=Html::cssFile('@web/css/index.css')?&gt;=Html::JSFile('@web/js/jquery.min.js')?&gt;

2、可以直接写原生代码引入,路径是项目目录/web/css 或者/js

<script></script>

3、可以使用assetBundle管理css样式及js脚本

资源包定义:basic/assets/AppAsset.php

<?php /**  * @link http://www.yiiframework.com/  * @copyright Copyright (c) 2008 Yii Software LLC  * @license http://www.yiiframework.com/license/  */  namespace appassets;  use yiiwebAssetBundle;  /**  * @author Qiang Xue <qiang.xue@gmail.com>  * @since 2.0  */  class AppAsset extends AssetBundle{      public $basePath = '@webroot';          public $baseUrl = '@web';          public $css = [              'css/site.css',              'css/base.css'     ];         public $js = [             'js/sliders.js'     ];         public $depends = [ //依赖包,没有可以不写         'yiiwebYiiAsset',                 'yiibootstrapBootstrapAsset',       ];      //定义按需加载JS方法,注意加载顺序在最后       public static function addScript($view, $jsfile) {           $view-&gt;registerJsFile($jsfile, [AppAsset::className(), 'depends' =&gt; 'apiassetsAppAsset']);       }             //定义按需加载css方法,注意加载顺序在最后       public static function addCss($view, $cssfile) {           $view-&gt;registerCssFile($cssfile, [AppAsset::className(), 'depends' =&gt; 'apiassetsAppAsset']);       }   }

在视图文件开头写入:

立即学习前端免费学习笔记(深入)”;

<?php use yiihelpersHtml;use appassetsAppAsset; AppAsset::register($this);  ?>

到现在为止,我们可以在浏览器上测试,发现并没有引入css和js文件,这里要注意了,我们还需要最后一步:

在视图文件中我们要加入一下代码(注:如果我们使用公共视图文件,可以加入到公共视图文件,如果没有使用,可以放到单独页面中)

<?php $this->beginPage() ?&gt;  <?php  $this->head() ?&gt; <?php  $this->beginBody() ?&gt;  <?php  $this->endBody() ?&gt; <?php  $this->endPage() ?&gt;

4、不需要在资源包管理器中定义方法,只要在视图页面中直接引入即可

AppAsset::register($this);   //css定义一样   $this-&gt;registerCssFile('@web/css/font-awesome.min.css',['depends'=&gt;['apiassetsAppAsset']]);       $this-&gt;registerJsFile('@web/js/jquery-ui.custom.min.js',['depends'=&gt;['apiassetsAppAsset']]);   //$this-&gt;registerJsFile('@web/js/jquery-ui.custom.min.js',['depends'=&gt;['apiassetsAppAsset'], 'position'=&gt;$this::POS_HEAD]);

相关文章教程推荐:yii教程

以上就是yii2怎么引入

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享