armnotstrong
armnotstrong

Reputation: 9065

Why a un-closed html tag make the html template not rendering in go?

I come to a very bothering problem, And it took me about an hour to figure what cause the problem, but I don't know why:

I am using html/template to rending a web page and the code is like this:

t, _ := template.parseFiles("template/index.tmpl")
...
t.Execute(w, modelView) // w is a http.ResponseWriter and modelView is a data struct.

But unconsciously, I made a mistake that leave a <textarea> tag open:

<html>
<body>
        <form id="batchAddUser" class="form-inline">
        **this one**  -->  <textarea name="users" value="" row=3 placeholder="input username and password splited by space">
            <button type="submit" class="btn btn-success" >Add</button>
        </form>
</body>
</html>

And then Go gives no exception and other hint, but just give a blank page with nothing, and the status code is 200.

It toke effect to locate the problem since no information was offered, but why is that happen? How comes a un-colsed tag cause problem like that? And how to debug that?

Upvotes: 3

Views: 343

Answers (2)

David Budworth
David Budworth

Reputation: 11626

It is telling you about the error, you are just ignoring it.

If you look at the error returned by Execute, it tells you that your html is bad.

You should always check for errors. Something like:

t, err := template.New("test").Parse(ttxt)
if err != nil { 
    ...do something with error...
}
err = t.Execute(os.Stdout, nil) // w is a http.R
if err != nil { 
    ...do something with error...
}

Here it is (with error printing) on Playground

Here it is, fixed on Playground

Upvotes: 6

Grzegorz Żur
Grzegorz Żur

Reputation: 49161

The Go's template package provides method Must that will make your program fail fast by panicking in case of such errors. You can free your code of some error checks, yet you will still be in control.

t := template.Must(template.parseFiles("template/index.tmpl"))

Upvotes: 3

Related Questions