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 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测