html / templates - 用< br>替换换行符 [英] html/templates - Replacing newlines with <br>

查看:388
本文介绍了html / templates - 用< br>替换换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



<在加载的字符串中用< br> 替换 \\\
,它们会被模板转义为html < br& gt; 并显示在浏览器中,而不会导致行返回。 如何在不切换到 text / templates (没有XSS保护)的情况下更改此行为?

解决方案

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



更新:在Kocka的示例中进行扩展,这是我想到的:

<$ p (
html / template
os
strings
)$(

$) b
$ b const page =`<!DOCTYPE html>
< html>
< head>
< / head>
< body>
< p> {{。}}< / p>
< / body>
< / html>`

const text =`第一行
< script>危险< / script>
最后一行

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 (安全))// template.HTML封装一个已知的安全HTML文档片段。
}

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



输出是

 <!DOCTYPE html> 
< html>
< head>
< / head>
< body>
< p>第一行< br>& lt; script& gt;危险& lt; / script& gt;< br>最后一行< / p>
< / body>
< / html>

浏览器中呈现的文字是

 第一行
< script>危险< / script>
最后一行


I'm loading a text file that has newlines in it, and pass it to html/templates.

Substituting the \n 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)?

解决方案

It seems you could run template.HTMLEscape() on your text first to sanitize it, then do the \n 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, "\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

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

这篇关于html / templates - 用&lt; br&gt;替换换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆