search

Home  >  Q&A  >  body text

How to not strip HTML comments in HTML template in gin gonic

I'm using Gin Gonic and an HTML template file.

My template file contains (multi-line) HTML comments similar to <!--This is my comment -->. I wish to preserve the HTML content in the returned output.

c.HTML(http.StatusOK, "static/templates/mytemplate.html", gin.H{
    "name": "World",
})

Question: How to configure the template engine or c.HTML to not strip HTML comments in templates?

More detailed answer

/static/templates/mytemplate.html:

<!DOCTYPE html>
<html lang="de">
<body>
<!--
这些行在输出中缺失。
-->
Hello World
</body>
</html>

My handler:

func NewRouter() *gin.Engine {
    router := gin.Default()
    // ... load templates from file system ...
    router.GET("/foo", fooHandler)
    return router
}
func fooHandler(c *gin.Context) {
    c.HTML(http.StatusOK, "static/templates/mytemplate.html", gin.H{
        "name": "World",
    })
}

After editing, I tried adding the annotation as a constant :

{{"<!-- my comment goes here -->"}}

but the tag is escaped as

<!-- foo --> 


P粉193307465P粉193307465525 days ago664

reply all(1)I'll reply

  • P粉237029457

    P粉2370294572023-07-19 16:31:03

    I'm guessing the reason the HTML comments are removed is because I'm reading the HTML template as a string (instead of directly as a file). The exact cause still cannot be determined. Anyway, the solution that worked for me was to use placeholders in the template.

    <!DOCTYPE html>
    <html lang="de">
    <body>
    {{ .myComment }}
    Hello World
    </body>
    </html>
    

    and pass the HTML comment itself as a parameter:

    const myHtmlComment string = `
    <!--
    these lines are (not) missing (anymore) in the output
    -->
    `
    func fooHandler(c *gin.Context) {
        c.HTML(http.StatusOK, "static/templates/mytemplate.html", gin.H{
            "name": "World",
            "myComment": template.HTML(myHtmlComment),
        })
    }
    

    Use import "html/template" to import

    reply
    0
  • Cancelreply