dongluoqiu0255 2012-09-27 22:47
浏览 44
已采纳

在Yii的PHP heredoc中使用函数调用的返回值?

I'm trying to html encode a string that will be used as a tooltip in a google map.

$cs = Yii::app()->getClientScript();
$cs->registerScript('someID', <<<EOD
    function mapsetup() {
        //...        
        var marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            // works:
            title: '$model->name'
            // doesn't work:
            title: '{${CHtml::encode($model->name)}}'
            });
       // ...
    }
    mapsetup();
EOD
, CClientScript::POS_LOAD
);

If I use the line title: '$model->name', it results in the following expansion:

title: 'Some Name'

If I instead use the line title: '{${CHtml::encode($model->name)}}', it results in the following expansion:

title: ''

CHtml::encode works elsewhere on the same page fine, but it doesn't seem to work in the php heredoc.

  1. Do I even need to html encode javascript string data that will be rendered to the browser?
  2. How can I get CHtml::encode to work in the heredoc?
  • 写回答

2条回答 默认 最新

  • drr25281 2012-09-27 23:34
    关注
    1. You do need to encode the data, but not with CHtml::encode. You have to use CJSON::encode or CJavaScript::encode instead (any one will do) because you are injecting values into JavaScript, not into HTML.
    2. You cannot get it to work. Just calculate the value you need beforehand, store it in a variable an inject the contents of the variable.

    So for example:

    $title = CJSON::encode($model->name);
    $cs = Yii::app()->getClientScript();
    $cs->registerScript('someID', <<<EOD
        function mapsetup() {
            //...        
            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: $title // no quotes! CJSON::encode added them already
                });
           // ...
        }
        mapsetup();
    EOD
    , CClientScript::POS_LOAD
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog