Yii2:: transform PHP vars to Jacascript


In my project I need to set some js vars from controller. after some search found the following class :

then I ported it from Laravel to Yii2

Now you can use it in your Yii2 application.

How to use :

1- Download Js.php

2- Put it into components directory

3- Use it!!

        $js = new Js($namespace='window',$pos=View::POS_HEAD);

        $js->put(['age' => 22, 'amount' => 22.3]);

Above code put the following js code into <head> tag.

<script type="text/javascript">window.age = 22;window.amount = 22.3;</script>

you can find source in

if it has any problem or you have any idea you can open an issue or clone,fix and send a PR.


Thanks, but what is the benefit of this? It seems like un-necessary usage of a Class for something super simple. What does it do that the following doesn’t?

$age = 22;

$amount = 22.3;

$vars = "window.age = {$age};window.amount = {$amount};";

$this->registerJs($vars, View::POS_END);