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
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,
...
}) }}