【发布时间】:2019-12-05 11:27:54
【问题描述】:
我在一个简单的 HTTP 服务器上玩 Go:
// var tpl = template.Must(template.New("").Funcs(template.FuncMap{"isRegistered": isRegistered}).ParseGlob("templates/*")) // functions will be added later
var tpl = template.Must(template.ParseGlob("templates/*"))
func contact(w http.ResponseWriter, r *http.Request) {
//// defined templates are: "home.html", "layout", "layout.html", "contact.html", "body"
log.Println("in handler: ", tpl.DefinedTemplates())
err := tpl.ExecuteTemplate(w, "contact.html", nil)
if err != nil {
fmt.Println(err) // no error displayed
}
// fmt.Fprintf((w), "write") - This works fine
}
func main() {
log.Println("Serving on 8888 port")
http.HandleFunc("/contact", contact)
http.ListenAndServe(":8888", nil)
}
{{define "layout"}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{.Title}}</title>
<meta name="description" content="{{.Description}}">
<link rel="canonical" href="{{.Canonical}}" />
</head>
<body>
{{template "body" .}}
</body>
</html>
{{end}}
{{define "body"}}
<h1>Contact us page</h1>
<p>
Your name is...
</p>
{{end}}
localhost:8888/contact 返回 OK 200 和空正文。 我用了这个例子:https://stackoverflow.com/a/36643663/2110953
但我以后还需要添加模板函数: var tpl = template.Must(template.New("").Funcs(template.FuncMap{"isRegistered": isRegistered}).ParseGlob("templates/*"))
【问题讨论】:
-
您没有在控制台上看到任何错误?
contact.html模板长什么样子? -
没有错误,这就是为什么要问...
-
请注意,Go 模板永远不会返回 200。他们完全不知道 HTTP 状态代码。
-
您必须在控制台中有一些输出。
-
谢谢,我知道,我的意思是完全没有错误,你看我的代码,我用模板更新了。
标签: templates go go-templates