英文:
<!DOCTYPE> html/template
问题
我有一个简单的Go语言Web服务器,它只是将一些数据解析到外部HTML文件中,并将该文件提供给Web服务器。
package main
import (
"html/template"
"net/http"
)
type Event struct {
Name string
}
func handler(w http.ResponseWriter, r *http.Request) {
e := Event{ Name: "Melt! Festival" }
t, _ := template.ParseFiles("events.html")
t.Execute(w, e)
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":1337", nil)
}
但是,每当我尝试解析带有<!DOCTYPE>
的HTML文件时,它会将我的HTML页面解析为文本,而不是在浏览器中呈现HTML。
<!DOCTYPE>
<html>
<head>
<title>Event</title>
</head>
<body>
<p>
Event: {{.Name}}
</p>
</body>
</html>
当我将<!DOCTYPE>
从HTML文件中删除时,它可以正常呈现。
有人能告诉我为什么会这样吗?我真的很好奇。我花了两个小时搜索我的Go代码不起作用的原因。
英文:
I've got this simple go lang webserver that does nothing more but parsing some data into an external HTML file and serve that file to the webserver.
package main
import (
"html/template"
"net/http"
)
type Event struct {
Name string
}
func handler(w http.ResponseWriter, r *http.Request) {
e := Event{ Name: "Melt! Festival" }
t, _ := template.ParseFiles("events.html")
t.Execute(w, e)
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":1337", nil)
}
But whenever I try to parse the HTML file with the <!DOCTYPE> set it parses my html-page as text in stead of rendering the HTML in the browser
<!DOCTYPE>
<html>
<head>
<title>Event</title>
</head>
<body>
<p>
Event: {{.Name}}
</p>
</body>
</html>
When I leave the <!DOCTYPE>
out of the HTML-file it renders it just fine.
Can anyone tell me why this is because I'm really curious? I spent two hours searching for the cause of my go code not working.
答案1
得分: 2
你的文档类型声明不正确,因此产生了与期望相反的效果:浏览器可能会将其解释为文档不是HTML。
使用以下声明:
<!DOCTYPE html>
参考资料1。
英文:
Your doctype declaration is incorrect, thus having an effect opposite from the desired one : it is probably interpreted by the browser as signifying the document isn't HTML.
Use this :
<!DOCTYPE html>
See reference.
答案2
得分: 0
你是否尝试在你的文件中使用DOCTYPE html?
英文:
Have you tried using DOCTYPE html in your file instead?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论