在此代码中,我创建了一个文件来停止每个文件中代码的重复。我在 和 中都正确使用了 和 。base.htmlHTML{{define ".."}}{{template ".." .}}home.htmlabout.html
但是当我运行代码并访问 或 时,它只给出文件的结果。尽管对于链接,它应该给出文件的结果。localhost:8080localhost:8080/abouthome.html/aboutabout.html
主要.go
func main() {
http.HandleFunc("/", handler.Home)
http.HandleFunc("/about", handler.About)
fmt.Println("Starting the server at :8080")
http.ListenAndServe(":8080", nil)
}
处理程序.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)
}
基地.html
{{define "base"}}
<!DOCTYPE html>
<html>
<head>
<title>{{template "title" .}}</title>
</head>
<body>
<section>
{{template "body" .}}
</section>
</body>
</html>
{{end}}
家.html
{{template "base" .}}
{{define "title"}} Home page {{end}}
{{define "body"}}
<h1>Home page</h1>
<p>This is the home page</p>
{{end}}
关于.html
{{template "base" .}}
{{define "title"}} About page {{end}}
{{define "body"}}
<h1>About page</h1>
<p>This is an about page</p>
{{end}}
哔哔one
相关分类