Reputation: 21174
In my JavaScript (using jQuery) there are a whole set of PHP variables to which I need access. While I've got it working by just producing the JavaScript file as a view, and then using renderPartial()
to echo the JavaScript inside the main view.
However, this is obviously not very elegant, so I would like to know the 'Yii' way of doing it. I've been looking at the Assets Manager but that seems to be for static JavaScript files - you can't include PHP in there (unless I'm wrong).
Is there another way of doing it?
Upvotes: 3
Views: 7686
Reputation: 1329
Refer to Yii2 - Client Scripts Documentation, you can use registerJS function to pass variables to javascipt. For example:
/* @var $this yii\web\View */
$this->registerJs(
"var calenderEvents = ".Json::encode($calenderEvents).";",
yii\web\View::POS_HEAD,
'calender-events-script'
);
Upvotes: 1
Reputation: 71
Try to do this that way:
$myVarList = array(
'nameOne'=>$valueFromAnotherVar,
'nameTwo'=>$object->coolValue,
'nameThree'=>$cat->hoursSleptToday()
);$json = addslashes(CJSON::encode($myVarList));
Yii::app()->clientScript->registerScript("myVarList", 'myVarList = jQuery.parseJSON("' . $json . '");');
Upvotes: 0
Reputation: 552
Setting your variables in a key=>value array and using CJSON::encode works really well. You can access all your variables via the object created by jQuery's parseJSON. For example:
$myVarList = array(
'nameOne'=>$valueFromAnotherVar,
'nameTwo'=>$object->coolValue,
'nameThree'=>$cat->hoursSleptToday()
);
Yii::app()->clientScript->registerScript("myVarList",
'myVarList = jQuery.parseJSON('.CJSON::encode($myVarList).');'
You can then access the values from the global var.
myVarList.nameOne || myVarList.nameTwo || myVarList.nameThree
Upvotes: 1
Reputation: 431
The one of approaches is to set global variable by a small script and redisterScript(), and then use this variable in real js
Upvotes: 1
Reputation: 1091
You may consider registerScript. In my opinion, it is better since there is a param named $position, which can help you control the process output of render().
Upvotes: 2
Reputation: 437376
There's nothing inherently wrong or inelegant with your approach, and yes assets are static content (JS, CSS, etc) -- unrelated to the issue.
Fundamentally you can only expose the value of a PHP variable in JS by writing it as part of PHP code. If you will only need this value in a limited scope then you could just write it as an inline constant (which is what e.g. some widgets do). If you need it to be available throughout your JS code the only option is to produce JS code like you do now.
It's not strictly necessary to make a new partial view for your PHP-to-JS variables, but it's also not a bad idea. If you are happy with it, by all means use it.
Upvotes: 2