看来您可以先在文本上运行template.HTMLEscape()进行净化,然后执行 n
替换所信任的内容,然后将其用作预先转义和信任的模板数据。
更新:在Kocka的示例上扩展,这是我想到的:
package mainimport ( "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.}http://play.golang.org/p/JiH0uD5Zh2
输出为
<!DOCTYPE html><html> <head> </head> <body> <p>first line<br><script>dangerous</script><br>last line</p> </body></html>
在浏览器中呈现的文本是
first line<script>dangerous</script>last line



