Passing variable into "on" method of a View

The yii\base\View have a "on" method, inside my view files I called it like this:

$var = "test";

$this->on(\yii\web\View::EVENT_END_PAGE, function() {

    echo $var;


But I get "Undefined variable: test" is I run that code. How can I pass a variable from outside to on method? This is the documentation of on method

public void on ( $name, $handler, $data = null, $append = true )

“$data” looks like what you’re after.

But I can I pass for example 2 variables I tryed like in render [‘var1’=>$var1, ‘var2’=>$var2] and don’t work.

Someone can provide an example?

Also you declare $var = ‘test’, but $test in the function.

I wrote the code directly here in the forum, this is not the problem. The problem is the one explained the $var is not accessible inside the "on" method.

I found how can I pass the variables is like this

$var1 = "test";


$this->on(\yii\web\View::EVENT_END_PAGE, function($e) {

    echo $e->data['var1'];

    echo $e->data['var2'];

},['var1' => $var1, 'var2'=>$var2]);