在Golang的HTML模板中,将`'`转义为`'`。

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

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&#39;</title>
    </head>
</html>

期望的输出结果:

<html>
    <head>
        <title>Hello World&#39;</title>
    </head>
</html>

playground

英文:

How to prevent escaping &#39; to &amp;#39; in html template:

package main

import (
	&quot;html/template&quot;
	&quot;os&quot;
)

const tmpl = `&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;{{.Title}}&lt;/title&gt;
    &lt;/head&gt;
&lt;/html&gt;`

func main() {
	t := template.Must(template.New(&quot;ex&quot;).Parse(tmpl))
	v := map[string]interface{}{
		&quot;Title&quot;: template.HTML(&quot;Hello World&#39;&quot;),
	}
	t.Execute(os.Stdout, v)
}

It outputs:

&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;Hello World&amp;#39;&lt;/title&gt;
    &lt;/head&gt;
&lt;/html&gt;

Desired output:

&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;Hello World&#39;&lt;/title&gt;
    &lt;/head&gt;
&lt;/html&gt;

playouground

答案1

得分: 1

@dyoo已经清楚地解释了<title>内容被视为RCDATA。执行转义的代码在这里if t == contentTypeHTML分支是处理template.HTML的情况。

如果你真的需要控制源代码的输出,请使用text/template并手动进行转义。

英文:

@dyoo has explained clearly that &lt;title&gt; 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.

huangapple
  • 本文由 发表于 2015年1月5日 17:24:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/27776525.html
匿名

发表评论

匿名网友

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

确定