我試圖創(chuàng)建一個(gè)處理程序,然后將編譯 2 個(gè)模板:用于布局目的的 template.html 和實(shí)際頁(yè)面:config.html。此代碼構(gòu)建頁(yè)面,但未傳遞任何數(shù)據(jù):func config(w http.ResponseWriter, r *http.Request) { fpTemplate := filepath.Join("static", "template.html") fpPage := filepath.Join("static", "config.html") tmpl, err := template.ParseFiles(fpPage, fpTemplate) if err != nil { log.Println("webserver.config: " + err.Error()) } vd := ViewData{&Settings} err = tmpl.ExecuteTemplate(w, "template.html", vd) if err != nil { log.Println("webserver.config: " + err.Error()) }}和 config.html 是這樣的:{{define "title"}} Config {{end}}{{define "body"}}<p class="text-break">{{ .}}</p>{{end}},當(dāng)我運(yùn)行這段代碼時(shí):func config(w http.ResponseWriter, r *http.Request) { fpTemplate := filepath.Join("static", "template.html") fpPage := filepath.Join("static", "config.html") //tmpl, err := template.ParseFiles(fpPage, fpTemplate) tmpl, err := template.New("config.html").ParseFiles(fpPage, fpTemplate) if err != nil { log.Println("webserver.config: " + err.Error()) } vd := ViewData{&Settings} err = tmpl.ExecuteTemplate(w, tmpl.Name(), vd) fmt.Println(err) //err = tmpl.ExecuteTemplate(w, "template.html", vd) if err != nil { log.Println("webserver.config: " + err.Error()) }}我收到錯(cuò)誤:模板:沒(méi)有與模板“config.html”關(guān)聯(lián)的模板“config.html”和空白黑頁(yè)。我在這里錯(cuò)過(guò)了什么?感謝任何幫助!
1 回答

慕標(biāo)琳琳
TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超9個(gè)贊
當(dāng)您在第一個(gè)代碼中將“vd”傳遞給 ExecuteTemplate 時(shí),數(shù)據(jù)傳遞給主模板,并且當(dāng)您在“template.html”上調(diào)用它時(shí),您必須將數(shù)據(jù)傳遞給“body”模板,如下所示:
{{ template "body" . }}
- 1 回答
- 0 關(guān)注
- 84 瀏覽
添加回答
舉報(bào)
0/150
提交
取消