Go - HTML comments are not rendered

前端 未结 2 1350
孤街浪徒
孤街浪徒 2020-12-21 05:15

I\'m building go web application. I found some anomaly on the rendered html page. All of my html comments are suddenly not being rendered. My gue

2条回答
  •  情话喂你
    2020-12-21 05:41

    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 = `
    {{safe ""}}
    
    Some HTML content
    `

    Output (try it on the Go Playground):

    
    
    
    Some HTML content

    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:

    
    

    To this:

    {{safe ""}}
    

    Or alternatively (whichever you like):

    {{"" | safe}}
    

    And you're good to go.

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

    {{safe ""}}
    

    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.

提交回复
热议问题