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条)

报告相同问题?

悬赏问题

  • ¥30 求给定范围的全体素数p的(p-2)的连乘积
  • ¥15 VFP如何使用阿里TTS实现文字转语音?
  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页