I have a simple Go HTML template which contains HTML conditional comments:
package main
import (
"html/template"
"os"
)
var body = `<!doctype html>
<html>
<head>
<!--[if !IE]><!--><script src="http://code.jquery.com/jquery-2.0.3.min.js"></script><!--<![endif]-->
<!--[if gte IE 9]><script src="http://code.jquery.com/jquery-2.0.3.min.js"></script><![endif]-->
<!--[if lt IE 9]><script src="http://code.jquery.com/jquery-1.10.2.min.js"></script><![endif]-->
</head>
</html>`
func main() {
tmp := template.Must(template.New("tmp").Parse(body))
tmp.Execute(os.Stdout, nil)
}
This produces:
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
</head>
</html>
Why does html/template
remove those conditional comments after compiling?
Since your question was Why, I will try to explain why comments are stripped away.
First of all, the purpose of the html/template
package is to be safe. The documentation states:
Package template (html/template) implements data-driven templates for generating HTML output safe against code injection.
This is done through context-sensitive escaping. In a Golang-nuts thread Kyle Lemons provide an example where conditional comments would currently break this safety unless the comments were stripped away:
<p>
<!--[if lt IE 9]><script><![endif]-->
{{.Stuff}}
<!--[if lt IE 9]></script><![endif]-->
</p>
In this case, any value in {{.Stuff}} will be executed as Javascript on some browsers and should therefore be escaped to be safe . This would require the template engine to be aware of this browser-specific interpretation of the comment, and any other non-standard behavior in all the browsers out there. This is not feasible.
Instead, html/template
was designed to strip away any comments to ensure that the HTML it produces is safe from any injection attack.
Workaround
As mentioned by Dave, it is possible to use template.HTML
to insert such comments. However, because of the security risk, the documentation for template.HTML
states (my emphasis):
HTML encapsulates a known safe HTML document fragment. It should not be used for HTML from a third-party, or HTML with unclosed tags or comments.
My workaround is to reimplement the noescape helper that was removed on commit #938597eab997
funcMap := template.FuncMap{
"noescape": func(s string) template.HTML {
return template.HTML(s)
},
}
and then use it in your template:
<!DOCTYPE html>
{{noescape "<!--[if lt IE 9]>"}}<html class="old-ie">{{noescape "<![endif]-->"}}
It looks that the problem was discussed on golang-nuts group:
https://groups.google.com/forum/#!msg/golang-nuts/8y6by6SERyU/XQRnbw3aBhwJ
TL;DR
Go html/template
strips of all html commments, and didn't interpret conditional comments since they are not a part of the standard.
Also the {{noescape}}
directive has been removed: http://code.google.com/p/go/issues/detail?id=3528
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With