Hey,
I use assets to bundle CSS and JS for specific functions and sub-pages of my Yii2 application.
From time to time I also need to pass an Yii-generated URL (like Url::toRoute([‘ajax/get’]) ) to Js-side using registerJsVar - method.
I’m not sure, where the best place for \Yii::$app->clientScript->registerJsVar
is, so i decided to put this in the init()
section of the related AssetBundle. Now CSS & JS files & JS parameters (like this url) er bundled in one place: the AssetBundle.
My init()
method of the bundle looks like that:
public function init()
{
parent::init();
$ajaxGetUrl = Url::toRoute(['ajax/get']);
\Yii::$app->clientScript->registerJsVar ('g_ajaxGetUrl', $ajaxGetUrl, \Yii::$app->clientScript::POS_HEAD);
}
But this will not work and I get the following error: " Getting unknown property: yii\web\Application::clientScript"
Any ideas how to fix this?
Is this the wrong place for registering JS vars?
Thank you.