英文:
Inserting HTML to golang template
问题
我有一个使用golang的模板,其中有一个字符串看起来像这样:
<some_html> {{ .SomeOtherHTML }} </some_html>
我期望的输出应该是这样的:
<some_html> <the_other_html/> </some_html>
但实际上我看到的是这样的:
<some_html> &lt;the_other_html/&lt; </some_html>
我还尝试插入一些JSON,但是golang会转义字符并在不应该出现的地方添加"
之类的东西。
如何在golang的HTML模板中插入内容而不会发生这种情况?
英文:
I have a template in golang where I have a string that looks something like this:
<some_html> {{ .SomeOtherHTML }} </some_html>
I'm expecting an output to be something like this:
<some_html> <the_other_html/> </some_html>
But instead I'm seeing something like this:
<some_html> &lt;the_other_html/&lt; </some_html>
I'm also trying to insert some JSON but golang is escaping characters and adding things like "
in places they shouldn't be.
How do I insert into an HTML template in golang without this happening?
答案1
得分: 26
你应该将变量作为template.HTML
而不是string
传递:
tpl := template.Must(template.New("main").Parse(`{{define "T"}}{{.Html}}{{.String}}{{end}}`))
tplVars := map[string]interface{}{
"Html": template.HTML("<p>Paragraph</p>"),
"String": "<p>Paragraph</p>",
}
tpl.ExecuteTemplate(os.Stdout, "T", tplVars)
// 输出: <p>Paragraph</p><p>Paragraph</p>
如你所见,我们作为template.HTML
传递的变量没有被转义,而作为string
传递的变量则被转义了。
英文:
You should pass the variable as a template.HTML
and not as a string
:
tpl := template.Must(template.New("main").Parse(`{{define "T"}}{{.Html}}{{.String}}{{end}}`))
tplVars := map[string]interface{} {
"Html": template.HTML("<p>Paragraph</p>"),
"String": "<p>Paragraph</p>",
}
tpl.ExecuteTemplate(os.Stdout, "T", tplVars)
//OUTPUT: <p>Paragraph</p>&lt;p&gt;Paragraph&lt;/p&gt;
https://play.golang.org/p/QKKpQJ7gIs
As you can see, the variable we passed as a template.HTML
is not escaped, but the one passed as a string
is.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论