如何在HTML模板中避免转义字符的问题。

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

How to not escape in HTML templates

问题

尝试使用嵌入附件的cid:来渲染用于通过电子邮件发送的HTML模板。问题是,Go语言会进行转义处理,我无法做任何操作。

tplVars := map[string]interface{}{
    "Dog": "cid:dog.png",
    "Cat": "cid:cat.png",
}

我的测试模板大致如下:

Dog: <img src="{{.Dog}}">
Cat: {{.Cat}}

输出结果为:

Dog: <img src="#ZgotmplZ">
Cat: cid:cat.png

如果文本位于属性上下文之外,它会被正确评估,但当它是src属性时,它总是变成错误字符串。我还尝试将值从string更改为template.HTMLAttr,但没有任何效果。cid的值始终被评估为错误输出#ZgotmplZ

英文:

Trying to render HTML templates for sending via email with embedded attachments with cid:. Problem is, that Go does escaping and I cannot do anything.

tplVars := map[string]interface{}{
    &quot;Dog&quot;: &quot;cid:dog.png&quot;,
    &quot;Cat&quot;: &quot;cid:cat.png&quot;,
}

My testing template looks more less like this:

Dog: &lt;img src=&quot;{{.Dog}}&quot;&gt;
Cat: {{.Cat}}

Output is:

Dog: &lt;img src=&quot;#ZgotmplZ&quot;&gt;
Cat: cid:cat.png

If text is outside attribute context, it is evaluated correctly, but when it is an src attribute it always become that error string. I tried also change value from string to template.HTMLAttr but nothing happen. Cid value is always evaluated to that error output #ZgotmplZ.

答案1

得分: 17

问题在于src属性并不被严格地视为属性,而是作为一个URL处理。如果你将它从string更改为template.URL,它就可以正常工作。

tplVars := map[string]interface{}{
    "Dog": template.URL("cid:dog.png"),
    "Cat": "cid:cat.png",
}

https://play.golang.org/p/ZN27nGnUE9

英文:

The issue is that the src attribute isn't treated strictly as an attribute, but as a URL. If you change it from a string to a template.URL it works just fine.

tplVars := map[string]interface{}{
	&quot;Dog&quot;: template.URL(&quot;cid:dog.png&quot;),
	&quot;Cat&quot;: &quot;cid:cat.png&quot;,
}

https://play.golang.org/p/ZN27nGnUE9

huangapple
  • 本文由 发表于 2016年4月29日 15:06:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/36931742.html
匿名

发表评论

匿名网友

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

确定