Yii2: Passing php variables to \yii\web\JsExpression()

Created on 24 Oct 2016  路  4Comments  路  Source: yiisoft/yii2

Hi,

I'm trying to use \yii\web\JsExpression() with highcharts and building a custom tooltip, I'm struggling to be able to pass PHP parameters to the function though. I have seen https://github.com/yiisoft/yii2/issues/9609. Is there a way to pass in a php variable so it can be used with \yii\web\JsExpression()

<?php
$var = 'hello';
'formatter' => \yii\web\JsExpression('function(){
       return {$var};
 }')
question

Most helpful comment

it should be done like this:

<?php
$var = 'hello';
'formatter' => \yii\web\JsExpression('function(){
       return ' . \yii\helpers\Json::htmlEncode($var) . ';
 }')

All 4 comments

doesnt the following fulfill your needs?:

<?php
$var = 'hello';
'formatter' => \yii\web\JsExpression('function(){
       return "'.$var.'";
 }')

It should be properly escaped or whitelisted though. Else you'll get into big trouble.

_This is an automated comment, triggered by adding the label question._

Please note, that the GitHub Issue Tracker is for bug reports and feature requests only.

We are happy to help you on the support forum, on IRC (#yii on freenode), or Gitter.

Please use one of the above mentioned resources to discuss the problem.
If the result of the discussion turns out that there really is a bug in the framework, feel free to
come back and provide information on how to reproduce the issue. This issue will be closed for now.

it should be done like this:

<?php
$var = 'hello';
'formatter' => \yii\web\JsExpression('function(){
       return ' . \yii\helpers\Json::htmlEncode($var) . ';
 }')
Was this page helpful?
0 / 5 - 0 ratings