在此代码中,我创建了一个文件来停止每个文件中代码的重复。我在 和 中都正确使用了 和 。base.htmlHTML{{define ".."}}{{template ".." .}}home.htmlabout.html但是当我运行代码并访问 或 时,它只给出文件的结果。尽管对于链接,它应该给出文件的结果。localhost:8080localhost:8080/abouthome.html/aboutabout.html主要.gofunc main() { http.HandleFunc("/", handler.Home) http.HandleFunc("/about", handler.About) fmt.Println("Starting the server at :8080") http.ListenAndServe(":8080", nil)}处理程序.gofunc 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}}
1 回答

哔哔one
TA贡献1854条经验 获得超8个赞
使用时必须单独创建模板,对于每个页面,包括基.html和页面.html:
var tmpl = make(map[string]*template.Template)
func init() {
tmpl["home"] = template.Must(template.ParseFiles("templates/home.html", "templates/base.html"))
tmpl["about"] = template.Must(template.ParseFiles("templates/about.html", "templates/base.html"))
}
func Home(w http.ResponseWriter, r *http.Request) {
tmpl["home"].ExecuteTemplate(w, "home.html", nil)
}
func About(w http.ResponseWriter, r *http.Request) {
tmpl["about"].ExecuteTemplate(w, "about.html", nil)
}
- 1 回答
- 0 关注
- 128 浏览
添加回答
举报
0/150
提交
取消