doushang9172 2012-12-08 15:45
浏览 329
已采纳

html / templates-用<br>替换换行符

I'm loading a text file that has newlines in it, and pass it to html/templates.

Substituting the with <br> in the loaded string, they are escaped by the template to html &lt;br&gt; and displayed in the browser, instead of causing a line return.

How can I change this behavior without switching to text/templates (which doesn't have XSS protection)?

  • 写回答

4条回答 默认 最新

  • douyunhuan9886 2012-12-08 21:59
    关注

    It seems you could run template.HTMLEscape() on your text first to sanitize it, then do the to
    substitution that you trust, then use that as pre-escaped and trusted template data.

    Update: Expanding on Kocka's example, this is what I had in mind:

    package main
    
    import (
        "html/template"
        "os"
        "strings"
    )
    
    const page = `<!DOCTYPE html>
    <html>
      <head>
      </head>
      <body>
        <p>{{.}}</p>
      </body>
    </html>`
    
    const text = `first line
    <script>dangerous</script>
    last line`
    
    func main() {
        t := template.Must(template.New("page").Parse(page))
        safe := template.HTMLEscapeString(text)
        safe = strings.Replace(safe, "
    ", "<br>", -1)
        t.Execute(os.Stdout, template.HTML(safe)) // template.HTML encapsulates a known safe HTML document fragment.
    }
    

    http://play.golang.org/p/JiH0uD5Zh2

    Output is

    <!DOCTYPE html>
    <html>
      <head>
      </head>
      <body>
        <p>first line<br>&lt;script&gt;dangerous&lt;/script&gt;<br>last line</p>
      </body>
    </html>
    

    And text rendered in the browser is

    first line
    <script>dangerous</script>
    last line
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题