溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

yii2框架加載靜態(tài)資源的方法

發(fā)布時間:2020-12-30 14:02:39 來源:億速云 閱讀:204 作者:小新 欄目:編程語言

小編給大家分享一下yii2框架加載靜態(tài)資源的方法,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

具體操作如下:

1、在 assets/AppAsset 里定義方法

<?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 = '@webroot';
    public $baseUrl = '@web';
 
    // 全局
    public $css = [
        
    ];
 
    // 全局
    public $js = [
        
    ];
 
    public $depends = [
        // 'yii\web\YiiAsset',
        // 'yii\bootstrap\BootstrapAsset',  // 注釋掉禁用bootstrap
    ];
 
    // 這是設(shè)置所有js放置的位置 
    public $jsOptions = [  
        'position' => \yii\web\View::POS_HEAD,    
    ]; 
 
    //定義按需加載JS方法
    public static function addJs($view, $jsfile) { 
        $view->registerJsFile(
            $jsfile, 
            [
                AppAsset::className(), 
                "depends" => "app\assets\AppAsset"
            ]
        ); 
    } 
 
    //定義按需加載css方法
    public static function addCss($view, $cssfile) { 
        $view->registerCssFile(
            $cssfile, 
            [
                AppAsset::className(), 
                "depends" => "app\assets\AppAsset"
            ]
        ); 
    } 
 
}

2、在view里調(diào)用

<?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);
 
// 按需加載css
AppAsset::addCss($this, Yii::$app->request->baseUrl."/css/site.css");
// 按需加載js
AppAsset::addJs($this, Yii::$app->request->baseUrl."/js/respond.min.js");
 
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
    <meta charset="<?= Yii::$app->charset ?>">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?= Html::csrfMetaTags() ?>
    <title><?= Html::encode($this->title) ?></title>
    <?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
 
        
    <?= $content ?>
 
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>

以上是“yii2框架加載靜態(tài)資源的方法”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI