Inserting HTML to golang template

huangapple go评论87阅读模式
英文:

Inserting HTML to golang template

问题

我有一个使用golang的模板,其中有一个字符串看起来像这样:

<some_html> {{ .SomeOtherHTML }} </some_html>

我期望的输出应该是这样的:

<some_html> <the_other_html/> </some_html>

但实际上我看到的是这样的:

<some_html> <the_other_html/< </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> <the_other_html/< </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>&lt;p&gt;Paragraph&lt;/p&gt;

如你所见,我们作为template.HTML传递的变量没有被转义,而作为string传递的变量则被转义了。

英文:

You should pass the variable as a template.HTML and not as a string:

tpl := template.Must(template.New(&quot;main&quot;).Parse(`{{define &quot;T&quot;}}{{.Html}}{{.String}}{{end}}`))
tplVars := map[string]interface{} {
    &quot;Html&quot;: template.HTML(&quot;&lt;p&gt;Paragraph&lt;/p&gt;&quot;),
    &quot;String&quot;: &quot;&lt;p&gt;Paragraph&lt;/p&gt;&quot;,
}
tpl.ExecuteTemplate(os.Stdout, &quot;T&quot;, tplVars)

//OUTPUT: &lt;p&gt;Paragraph&lt;/p&gt;&amp;lt;p&amp;gt;Paragraph&amp;lt;/p&amp;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 stringis.

huangapple
  • 本文由 发表于 2017年1月30日 15:49:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/41931082.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定