在此代碼中,我創建了一個文件來停止每個文件中代碼的重復。我在 和 中都正確使用了 和 。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 關注
- 122 瀏覽
添加回答
舉報
0/150
提交
取消