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

报告相同问题?