dongqishun6409 2016-05-02 10:16
浏览 211

避免在HTML模板中自动转义

Trying to render HTML template with an URL. The problem is that the URL contains () in it, and those characters are escaped.

I tried to use template.URL("http://myurl.com/(data)/aaa.jpg") and also template.HTML("http://myurl.com/(data)/aaa.jpg") but it still escape brackets.

I'm using gin gonic.

router.GET("/test", func(c *gin.Context) {
    c.HTML(http.StatusOK, "test.tmpl", gin.H{
        "url": template.URL("http://myurl.com/(data)/aaa.jpg"),
        // "url": template.HTML("http://myurl.com/(data)/aaa.jpg"),
})

Template file :

<div>
  <img src="{{.url}}" />
</div>

final ouput :

<div>
  <img src="http://myurl.com/%28data%29/aaa.jpg"/>
</div>
  • 写回答

1条回答 默认 最新

  • duankui1532 2016-05-02 10:33
    关注

    Using a value of template.URL is perfectly enough.

    What you see is not HTML encoding of the given URL, what you see is the URL encoding of the opening and closing parenthesis in the (data) part. That is perfectly ok. %28 is the encoding of '(' (28 is the hexa code for the opening parenthesis character), and %29 is the ')' character.

    The url http://myurl.com/(data)/aaa.jpg and http://myurl.com/%28data%29/aaa.jpg are one and the same.

    The purpose of the URL encoding is so that URLs and values included in URLs (e.g. form parameters) can be safely transmitted.

    URL Encoding

    URLs can only be sent over the Internet using the ASCII character-set.

    Since URLs often contain characters outside the ASCII set, the URL has to be converted into a valid ASCII format.

    URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.

    You can read more about URL encoding here: HTML URL Encoding Reference.

    Testing it:

    func rh(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, `<html><body>
    <img src="http://localhost:8080/(data)/aaa.jpg">
    <img src="http://localhost:8080/%28data%29/aaa.jpg">
    </body></htm>`)
    }
    
    func imgh(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "aaa.jpg")
    }
    
    func main() {
        http.HandleFunc("/", rh)
        http.HandleFunc("/(data)/aaa.jpg", imgh)
        panic(http.ListenAndServe("localhost:8080", nil))
    }
    

    Now direct your browser to http://localhost:8080. It will display 2 images.

    评论

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图