2015-11-19 82 views
1

我想用它的css和js文件在yii2中創建一個自定義小部件。 'components'文件夾裏面我創建了一個'myWidget'文件夾,裏面有: - myWidget.php,它擴展了yii \ base \ Widget。 - myWidgetAsset.php,它擴展了yii \ web \ AssetBundle。 - 查看包含index.php文件的文件夾。 - 資產文件夾包含main.css和main.js文件。如何在Yii2中註冊widget資源?

這裏是代碼:myWidget.php

namespace app\components\myWidget; 

use app\components\tablaFoS\tablaFoSAsset; 
use app\models\DisciplinesGrandesAreas; 
use yii\base\Widget; 

class myWidget extends Widget { 

    public function run() { 
    parent::run(); 

    return $this->render('index'); 
    } 
} 

myWidgetAsset.php

namespace app\components\myWidget; 

use yii\web\AssetBundle; 

class myWidgetAsset extends AssetBundle { 

    public $basePath = '@webroot'; 
    public $baseUrl = '@web'; 
    public $css = ['assets/main.css']; 
    public $js = ['assets/main.js']; 
    public $depends = [ 
    ]; 
} 

當我看到生成的代碼我:

<link rel="stylesheet" href="/assets/main.css"></link> 
<script src="/assets/main.js"></script> 

,而不是像如引導程序:

<link href="/becyt/assets/67099f30/css/bootstrap.css" rel="stylesheet"> 

我在做什麼錯?我錯過了什麼?提前致謝。

+0

你看上去永遠不會註冊您的AssetBundle。我想你缺少的是myWidgetAsset :: register($ this-> view);'在你調用'return $ this-> render('index')之前''但是,我被困在同樣的問題上,我的js和css資產根本沒有註冊,所以如果其他任何人都可以參加,我也會非常感激。 –

回答

0

要發佈您的資產文件,您應該設置sourcePath而不是basePathbaseUrl,例如, :

class myWidgetAsset extends AssetBundle { 
    public $sourcePath = '@app/components/myWidget/assets'; 
    public $css = ['main.css']; 
    public $js = ['main.js']; 
} 

瞭解更多官方指南here

源資產:資產文件上無法通過網絡直接訪問PHP源代碼 位於一起。爲了在頁面中使用資源 ,應將它們複製到Web目錄並將 轉換爲所謂的已發佈資產。

當然,不要忘記在你的小工具run()方法中註冊這個資產包。

+0

它的工作!非常感謝soju! – Teleuko

0

您也可以註冊一個小部件資產像

<?php 
use yii\helpers\Html; 
use yii\helpers\Url; 
use yii\widgets\ActiveForm; 
\marqu3s\summernote\SummernoteAsset::register($this); 
1

你可以在註冊窗口小部件的init()功能您AssetBundle這樣的:

public function init() { 
    MyAssetBundle::register($this->getView()); 
    parent::init(); 
} 
相關問題