Go - HTML comments are not rendered

点点圈 提交于 2019-11-29 14:25:23

There is a special type in the html/template package: template.HTML. Values of this type in the template are not escaped when the template is rendered.

So you may "mark" your HTML comments as template.HTML and so they will not be escaped or omitted during executing your template.

One way to do this is to register a custom function for your template, a function which can be called from your template which takes a string argument and returns it as template.HTML. You can "pass" all the HTML comments to this function, and as a result, your HTML comments will be retained in the output.

See this example:

func main() {
    t := template.Must(template.New("").Funcs(template.FuncMap{
        "safe": func(s string) template.HTML { return template.HTML(s) },
    }).Parse(src))
    t.Execute(os.Stdout, nil)
}

const src = `<html><body>
{{safe "<!-- This is a comment -->"}}
<div>Some <b>HTML</b> content</div>
</body></html>`

Output (try it on the Go Playground):

<html><body>
<!-- This is a comment -->
<div>Some <b>HTML</b> content</div>
</body></html>

So basically after registering our safe() function, transform all your HTML comments to a template action calling this safe() function and passing your original HTML comment.

Convert this:

<!-- Some HTML comment -->

To this:

{{safe "<!-- Some HTML comment -->"}}

Or alternatively (whichever you like):

{{"<!-- Some HTML comment -->" | safe}}

And you're good to go.

Note: If your HTML comment contains quotation marks ('"'), you can / have to escape it like this:

{{safe "<!-- Some \"HTML\" comment -->"}}

Note #2: Be aware that you shouldn't use conditional HTML comments as that may break the context sensitive escaping of html/template package. For details read this.

You can use text/template instead of html/template and do all escaping manually using built-in functions such as html and js (https://golang.org/pkg/text/template/#hdr-Functions). Be aware that this is very error prone though.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!