英文:
escaping ' to ' in golang html template
问题
如何防止在HTML模板中将'
转义为'
:
package main
import (
"html/template"
"os"
)
const tmpl = `<html>
<head>
<title>{{.Title}}</title>
</head>
</html>`
func main() {
t := template.Must(template.New("ex").Parse(tmpl))
v := map[string]interface{}{
"Title": template.HTML("Hello World'"),
}
t.Execute(os.Stdout, v)
}
输出结果:
<html>
<head>
<title>Hello World'</title>
</head>
</html>
期望的输出结果:
<html>
<head>
<title>Hello World'</title>
</head>
</html>
英文:
How to prevent escaping '
to &#39;
in html template:
package main
import (
"html/template"
"os"
)
const tmpl = `<html>
<head>
<title>{{.Title}}</title>
</head>
</html>`
func main() {
t := template.Must(template.New("ex").Parse(tmpl))
v := map[string]interface{}{
"Title": template.HTML("Hello World'"),
}
t.Execute(os.Stdout, v)
}
It outputs:
<html>
<head>
<title>Hello World&#39;</title>
</head>
</html>
Desired output:
<html>
<head>
<title>Hello World'</title>
</head>
</html>
答案1
得分: 1
@dyoo已经清楚地解释了<title>
内容被视为RCDATA。执行转义的代码在这里。if t == contentTypeHTML
分支是处理template.HTML
的情况。
如果你真的需要控制源代码的输出,请使用text/template
并手动进行转义。
英文:
@dyoo has explained clearly that <title>
content is treated as RCDATA. The code that does the escaping is here. The branch if t == contentTypeHTML
is what happens with template.HTML
.
If you really need to control the output of the source, use text/template
and do the escaping manually.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论