英文:
Why a un-closed html tag make the html template not rendering in go?
问题
我遇到了一个非常困扰的问题,花了大约一个小时才找出问题的原因,但我不知道为什么:
我正在使用html/template
来渲染一个网页,代码如下:
t, _ := template.ParseFiles("template/index.tmpl")
...
t.Execute(w, modelView) // w 是一个 http.ResponseWriter,modelView 是一个数据结构
但是不知不觉中,我犯了一个错误,留下了一个未闭合的<textarea>
标签:
<html>
<body>
<form id="batchAddUser" class="form-inline">
**这里** --> <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>
然后 Go 没有抛出任何异常或提示,只是给了一个空白页面,状态码是200
。
由于没有提供任何信息,很难定位问题,但为什么会发生这种情况呢?一个未闭合的标签怎么会引起这样的问题?如何调试这个问题?
英文:
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?
答案1
得分: 6
它正在告诉你有关错误的信息,而你只是忽略了它。
如果你查看Execute返回的错误,它会告诉你你的HTML有问题。
你应该始终检查错误。像这样:
t, err := template.New("test").Parse(ttxt)
if err != nil {
// 处理错误...
}
err = t.Execute(os.Stdout, nil) // w 是一个 http.ResponseWriter
if err != nil {
// 处理错误...
}
这是带有错误打印的示例,在Playground上查看。
这是修复后的示例,在Playground上查看。
英文:
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
答案2
得分: 3
Go的模板包提供了一个名为Must
的方法,它可以在出现错误时通过引发恐慌来使程序快速失败。你可以减少代码中的一些错误检查,但仍然可以保持控制。
t := template.Must(template.ParseFiles("template/index.tmpl"))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论