4

I am using golang to add contents to the html template files. The main file is simple

func main() {
    server := http.Server{
        Addr: "localhost:8080",
    }

    http.HandleFunc("/process", processCover)
    server.ListenAndServe()
}

func processCover(w http.ResponseWriter, r *http.Request) {
    t1, _ := template.ParseFiles("t1.html", "t2.html")
    t1.Execute(w, "hello World")
}

In the html file, if I add the following code

<!-- {{ range . }}
<li>{{ . }}</li>
{{ end }} -->

The items after it are all missing. I don't get it because I think this is commented. It should be some bullet point I don't know about go web.

0

1 Answer 1

2

HTML comments in templates are not rendered if the context of the output is HTML. Since you put your {{range}} in HTML comment (between <!-- and -->) and since the output is an HTML document, it is stripped.

This is hinted in the doc of Template.Parse():

A template definition with a body containing only white space and comments is considered empty and will not replace an existing template's body.

See related: Go - HTML comments are not rendered

4
  • So do you mean because of the above reason you mentioned, all the items after this comment are skipped? Why couldn't it just skip the contents right in the comments?
    – Qiang Yao
    Jan 23, 2021 at 22:33
  • 1
    I think the correct way to comment a template item is {{/* */}}, although it will miss from the browser.
    – Qiang Yao
    Jan 23, 2021 at 22:45
  • @QiangYao if you want to produce output with HTML comments you can use custom template functions. play.golang.org/p/ZJMnjKk_XKK
    – mkopriva
    Jan 24, 2021 at 5:09
  • @mkopriva I just happened to comment the template definitions for convenience, but yours is definitely a good trick to learn.
    – Qiang Yao
    Jan 24, 2021 at 6:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.