使用Go的html /模板,白名单标签免于逃脱 [英] Whitelist tags exempt from escaping using Go's html/template
问题描述
将一个[]字节传递给模板,作为论坛式Web应用程序中消息帖子的主体。在模板中,调用一个方法将其转换为字符串,并沿途切换为换行符的所有换行符:
< p为H. {{BodyString}}< / p为H.
...
func(p * Post)BodyString()string {
nl:= regexp.MustCompile(`\ n`)
return nl.ReplaceAllString(string(p.Body), `< br>`)
}
你会得到什么结果:
段落< br> < br>中的< br> < br>这< br> < br>发布
我不想使用HTML传递整篇文章(p。正文),因为它代表来自可能不可靠来源的第三方数据。有没有一种方法可以将使用vanilla Go1模板包的只有一些标签用于格式化?
解析HTML。例如,exp / html中的HTML解析器被认为是不完整的,并从Go 1中移除,尽管exp树仍然在Go源树中,并且可以按周标签访问。我不知道什么是不完整的。我曾经用它做过一个简单的任务,它满足了我的需求。当然,请查看信息中心和看到相关的SO帖子,任何聪明的方法来获得exp / html返回Go1之后?,主要是为了推荐 http:/ /code.google.com/p/go-html-transform/
Pass a []byte into a template as the body of a message post on a forum-style web app. In the template, call a method to convert to string and along the way, switch out all newlines for line breaks:
<p>{{.BodyString}}</p>
...
func (p *Post) BodyString() string {
nl := regexp.MustCompile(`\n`)
return nl.ReplaceAllString(string(p.Body), `<br>`)
}
What you'll end up with:
paragraphs <br> <br>in <br> <br>this <br> <br>post
I don't want to pass the entire post in with HTML(p.Body), as it represents third party data from potentially untrustworthy sources. Is there a way to whitelist only some tags for formatting purposes using the vanilla Go1 template package?
I do think you want to parse the HTML. The HTML parser in exp/html was deemed incomplete and so removed from Go 1, although the exp tree is still in the Go source tree and can be accessed by weekly tag, for example. I don't know exactly what is incomplete. I used it for a simple task once and it met my needs.
Also of course, check the dashboard and see related SO post, Any smart method to get exp/html back after Go1?, mostly for the recomendation of http://code.google.com/p/go-html-transform/
这篇关于使用Go的html /模板,白名单标签免于逃脱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!