dptpn06684 2017-05-16 10:33
浏览 178
已采纳

如何阻止HTML模板转义

I have an html template where i want to insert some JavaScript code from outside of template itself. In my template data struct i have created a string field JS string and call it with {{.JS}}. The problem is that everything in browser is escaped:

newlines are

< and > are \u003c and \u003e

" is \"

Same symbols inside of a template are fine. If I Print my JS field into console it is also fine. I have seen some similar problems solved by using template.HTML type instead of string. In my case it does not work at all.

EDIT 1

The actual context is

<script language="JavaScript">
    var options = {
        {{.JS}}
    };
</script>
  • 写回答

2条回答 默认 最新

  • dongxia5394 2017-05-16 10:46
    关注

    Either change the field's type to template.JS like so:

    type Tmpl struct {
        // ...
        JS template.JS
    }
    

    Or declare a simple function that converts a string to the template.JS type like so:

    func toJS(s string) template.JS {
        return template.JS(s)
    }
    

    And then register the function with the Funcs method and use it in your template like so:

    {{toJS .JS}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部