Qiang Yao
Qiang Yao

Reputation: 185

html file cannot work if {{ end }} is added

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.

Upvotes: 4

Views: 100

Answers (1)

icza
icza

Reputation: 418505

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

Upvotes: 2

Related Questions