2

I'm using Gin Gonic with a HTML template file.

My template file contains (multi line) HTML comments of the kind <!-- my comment goes here-->. I want that the HTML content is preserved in the output which is returned by

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

where c is a *gin.Context.

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

More Detailed

/static/templates/mytemplate.html:

<!DOCTYPE html>
<html lang="de">
<body>
<!--
these lines are missing in the output
-->
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",
    })
}

Edit I tried to add the comments as constants:

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

But then the tags are escaped as

&lt;!-- foo --&gt;
koks der drache
  • 1,398
  • 1
  • 16
  • 33

1 Answers1

1

I guess the reason why the HTML comment is stripped is because I read the HTML template as string (instead of as file directly). Still cannot nail it down exactly. Anyway, the workaround that did the job for me, was to use a place holder in the template:

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

And pass the HTML comment itself as 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),
    })
}

with import "html/template"

koks der drache
  • 1,398
  • 1
  • 16
  • 33