ReferenceError: $ is not defined yii2

前端 未结 2 1517
无人及你
无人及你 2021-02-01 15:22

Adding a javascript inside my view results in the ReferenceError: $ is not defined. I assume that the problem is due to Yii2 injects scripts last on my page. How to

2条回答
  •  佛祖请我去吃肉
    2021-02-01 15:46

    Whenever you need some assets for a library specific use, register them in the view file like this:

    use yii\web\JqueryAsset;
    JqueryAsset::register(this);
    

    Alternatively, if you add yii\web\JqueryAsset to your $depends attribute inside AppAsset, the asset will be loaded automatically for all your views, given that you registered it in the main layout (by default in Yii2 boilerplate).

    I wanted to use the yii2-date-range from kartik-v in my project, and did this:

    use kartik\daterange\DateRangePicker;
    use kartik\daterange\MomentAsset;
    use yii\web\JqueryAsset;
    
    JqueryAsset::register(this);
    MomentAsset::register(this);
    ...
    echo DateRangePicker::widget([ 
        'model' => $model, 
        ...
    ]);
    

    Since I switched to twig templating, I ended up with the following code in my view:

    {{ use('kartik/daterange/DateRangePicker') }}
    {{ use('kartik/daterange/MomentAsset') }}
    {{ use('yii/web/JqueryAsset') }}
    {{ register_jquery_asset() }}
    {{ register_moment_asset() }}
    ...
    {{ date_range_picker_widget({ 
        'model': model, 
        ...
       }) }}
    

提交回复
热议问题