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

toa*_*kes 7 html templates go

我正在加载一个包含换行符的文本文件,并将其传递给html/templates.

在加载的字符串中替换\nwith <br>,它们将被模板转义为html &lt;br&gt;并显示在浏览器中,而不是导致行返回.

如何在不切换到text/templates(没有XSS保护)的情况下更改此行为?

Son*_*nia 8

您似乎可以先在文本上运行template.HTMLEscape()来清理它,然后对
您信任的替换执行\n ,然后将其用作预转义和可信模板数据.

更新:扩展Kocka的例子,这就是我的想法:

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, "\n", "<br>", -1)
    t.Execute(os.Stdout, template.HTML(safe)) // template.HTML encapsulates a known safe HTML document fragment.
}
Run Code Online (Sandbox Code Playgroud)

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

输出是

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <p>first line<br>&lt;script&gt;dangerous&lt;/script&gt;<br>last line</p>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

在浏览器中呈现的文本是

first line
<script>dangerous</script>
last line
Run Code Online (Sandbox Code Playgroud)