How to not strip HTML comments in HTML template in gin gonic
P粉193307465
P粉193307465 2023-07-18 19:17:03
0
1
700

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粉193307465
P粉193307465

reply all(1)
P粉237029457

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template