Yii2包含由widget生成的代码之后的资产

时间:2015-01-22 15:45:02

标签: yii2 yii-extensions yii-widgets

如何在视图文件中的Datepicker小部件生成的javascript代码之后包含我的.js文件。

            echo DatePicker::widget([
                'name'  => 'datepicker--2',
                'id' => 'datepicker--2',
                'clientOptions' => [
                    'showOtherMonths' => true,
                    'maxDate' => '+ 0d',
                    'showOtherMonths' => true,
                    'selectOtherMonths' => true,
                ]
            ]);

我的资产包:

namespace app\assets;

use yii\web\AssetBundle;

class ChartsAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $js = [
        'js/charts.js',
        'js/charts-init.js',
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\jui\JuiAsset',
        'yii\web\JqueryAsset',
    ];
}

我在页面来源上得到了什么:

...
<script src="/new/js/charts.js"></script>
<script src="/new/js/charts-init.js"></script>
<script type="text/javascript">jQuery(document).ready(function () {
$('#datepicker--2').datepicker($.extend({}, {"showOtherMonths":true,"maxDate":"+ 0d","selectOtherMonths":true,"dateFormat":"M d, yy"}));
});</script></body>
</html>

2 个答案:

答案 0 :(得分:4)

使用yii2,您可以选择在文档中定义客户端脚本的position(HEAD,BEGIN OR END)。这可以通过做这样的事情来实现

public $jsOptions = [
        'position' => \yii\web\View::POS_HEAD
 ];

或使用This.

答案 1 :(得分:1)

像这样创建BaseAssets

namespace app\assets;

class BaseAsset extends AssetBundle
{
    public $sourcePath = '@resources'; // @app/resources
    public $css = [];  
    public $js = [];    
    public $depends = [
        'yii\web\YiiAsset',
        'yii\jui\JuiAsset',
        'yii\web\JqueryAsset',
    ];         
    public $jsOptions = [ 'position' => \yii\web\View::POS_HEAD ];
}

您的Assets

namespace app\assets;

use yii\web\AssetBundle;

class ChartsAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $js = [
        'js/charts.js',
        'js/charts-init.js',
    ];
    public $depends = [
        'app\assets\BaseAssets',        
    ];
    public $jsOptions = [ 'position' => \yii\web\View::POS_END ];
}