我正在加载一个包含换行符的文本文件,并将其传递给 html/templates
.
替换 \n
与 <br>
在加载的字符串中,它们被模板转义为 html <br>
并显示在浏览器中,而不是导致换行。
如何在不切换到 text/templates
的情况下更改此行为? (没有 XSS 保护)?
最佳答案
看来您可以先在您的文本上运行 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.
}
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
关于html/templates - 用 <br> 替换换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13779027/