我正在加载一个包含换行符的文本文件,并将其传递给html/templates
.
替换为\n
with <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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)