为什么未关闭的html标记会使html模板无法呈现?

arm*_*ong 3 go go-html-template

我遇到了一个非常麻烦的问题,我花了大约一个小时来确定导致问题的原因,但我不知道为什么:

html/template用来翻页网页,代码是这样的:

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

但不知不觉中,我犯了一个错误,让<textarea>标签打开:

<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>
Run Code Online (Sandbox Code Playgroud)

然后Go没有给出任何异常和其他提示,但只是给出一个没有任何内容的空白页面,状态代码是200.

由于没有提供任何信息,它可以解决问题,但为什么会这样呢?一个未着色的标签怎么会引起这样的问题呢?以及如何调试?

Dav*_*rth 6

它告诉你错误,你只是忽略它.

如果你查看Execute返回的错误,它会告诉你你的HTML是坏的.

您应该始终检查错误.就像是:

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...
}
Run Code Online (Sandbox Code Playgroud)

这是Playground上的(有错误打印)

这是固定在Playground上的

  • 请注意,从`t.Execute`中捕获错误会使您处于棘手的位置 - 由于http.ResponseWriter已经被写入,因此实际向用户显示错误为时已晚.处理此问题的常用方法是创建您写入的缓冲池(如果失败,发送HTTP 500),然后执行`io.Copy(w,bufpool)`以写出执行的模板. (2认同)