【发布时间】:2021-10-14 15:58:21
【问题描述】:
在这段代码中,我创建了一个base.html 文件来阻止HTML 代码在每个文件中的重复。我在home.html 和about.html 中都正确使用了{{define ".."}} 和{{template ".." .}}。
但是当我运行代码并访问localhost:8080 或localhost:8080/about 时,它只给出home.html 文件的结果。虽然对于/about 链接,它应该给出about.html 文件的结果。
main.go
func main() {
http.HandleFunc("/", handler.Home)
http.HandleFunc("/about", handler.About)
fmt.Println("Starting the server at :8080")
http.ListenAndServe(":8080", nil)
}
handler.go
func init() {
tmpl = template.Must(template.ParseGlob("templates/*.html"))
}
func Home(w http.ResponseWriter, r *http.Request) {
tmpl.ExecuteTemplate(w, "home.html", nil)
}
func About(w http.ResponseWriter, r *http.Request) {
tmpl.ExecuteTemplate(w, "about.html", nil)
}
base.html
{{define "base"}}
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{template "title" .}}</title>
</head>
<body>
<section>
{{template "body" .}}
</section>
</body>
</html>
{{end}}
home.html
{{template "base" .}}
{{define "title"}} Home page {{end}}
{{define "body"}}
<h1>Home page</h1>
<p>This is the home page</p>
{{end}}
about.html
{{template "base" .}}
{{define "title"}} About page {{end}}
{{define "body"}}
<h1>About page</h1>
<p>This is an about page</p>
{{end}}
【问题讨论】:
-
您需要展示如何注册您的 HTTP 处理程序。
-
这里已经回答了这个问题:stackoverflow.com/questions/11467731/…