首頁  >  文章  >  php框架  >  yii2怎麼引入css和js文件

yii2怎麼引入css和js文件

王林
王林原創
2019-12-17 16:19:482598瀏覽

yii2怎麼引入css和js文件

引入方式有多種:

1、可以直接在檢視頁面上引入

<?php use yii\helpers\Html;?><?=Html::cssFile(&#39;@web/css/index.css&#39;)?><?=Html::jsFile(&#39;@web/js/jquery.min.js&#39;)?>

2 、可以直接寫原生程式碼引入,路徑是專案目錄/web/css 或/js

<script src="js/nav.js"></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 app\assets; 
use yii\web\AssetBundle; 
/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
 class AppAsset extends AssetBundle{
     public $basePath = &#39;@webroot&#39;;    
     public $baseUrl = &#39;@web&#39;;    
     public $css = [        
     &#39;css/site.css&#39;,        
     &#39;css/base.css&#39;
    ];    
    public $js = [        
    &#39;js/sliders.js&#39;
    ];    
    public $depends = [ //依赖包,没有可以不写
        &#39;yii\web\YiiAsset&#39;,        
        &#39;yii\bootstrap\BootstrapAsset&#39;,  
    ]; 
    //定义按需加载JS方法,注意加载顺序在最后  
    public static function addScript($view, $jsfile) {  
        $view->registerJsFile($jsfile, [AppAsset::className(), &#39;depends&#39; => &#39;api\assets\AppAsset&#39;]);  
    }  
      
   //定义按需加载css方法,注意加载顺序在最后  
    public static function addCss($view, $cssfile) {  
        $view->registerCssFile($cssfile, [AppAsset::className(), &#39;depends&#39; => &#39;api\assets\AppAsset&#39;]);  
    }  
}

在視圖文件開頭寫入:

<?php
use yii\helpers\Html;use app\assets\AppAsset;
AppAsset::register($this); 
?>

到現在為止,我們可以在瀏覽器上測試,發現並沒有引入css和js文件,這裡要注意了,我們還需要最後一步:

在視圖文件中我們要加入一下程式碼(註:如果我們使用公共視圖文件,可以加入到公共視圖文件,如果沒有使用,可以放到單獨頁面中)

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

4、不需要在資源包管理器中定義方法,只要在視圖頁面中直接引入即可

AppAsset::register($this);  
//css定义一样  
$this->registerCssFile(&#39;@web/css/font-awesome.min.css&#39;,[&#39;depends&#39;=>[&#39;api\assets\AppAsset&#39;]]);  
  
 $this->registerJsFile(&#39;@web/js/jquery-ui.custom.min.js&#39;,[&#39;depends&#39;=>[&#39;api\assets\AppAsset&#39;]]);  
//$this->registerJsFile(&#39;@web/js/jquery-ui.custom.min.js&#39;,[&#39;depends&#39;=>[&#39;api\assets\AppAsset&#39;],
&#39;position&#39;=>$this::POS_HEAD]);

相關文章教學建議: yii教學

以上是yii2怎麼引入css和js文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn