我在 Golang 項(xiàng)目中有 3 個(gè)文件,想法是在 layout.html 的正文中呈現(xiàn) index.html。有用。但是當(dāng)我嘗試將變量傳遞給index.html 時(shí),console.log()沒(méi)有呈現(xiàn)。當(dāng)我移動(dòng)console.log()到layout.html 時(shí),我可以從.html中看到 JSON 的內(nèi)容.tes。這是項(xiàng)目文件。布局.html<!DOCTYPE html><html><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{{.title}} | {{.project_name}}</title></head><body style="width:100%; height: 100%; overflow-x: visible"><div id="wrapper" style="width:100%; height:100%; margin: 0 auto"> {{template "contents"}}</div></body></html>索引.html{{define "contents"}}<script> var x = {{.tes}}; console.log(x)</script>{{end}}路由器.gofunc init() { // handler http.HandleFunc("/", RenderPage)}func RenderPage(w http.ResponseWriter, r *http.Request) { tes := map[string]interface{}{ "item":"TEST3", "count":4567, } Data := map[string]interface{}{ "title":"TEST1", "project_name":"TEST2", "tes":M.ToJSON(tes), } tmpl, err := template.ParseFiles("page/layout.html", "page/index.html") X.CheckError(err) err = tmpl.Execute(w, Data) X.CheckError(err)}
1 回答

Qyouu
TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超11個(gè)贊
在 layout.HTML 中,您需要傳遞上下文。你用一個(gè).
點(diǎn)來(lái)做。
{{ template "contents" . }}
或者,您可以傳遞您想要的任何 var 的值:
{{ template "contents" .tes }}
...在內(nèi)容模板中,點(diǎn)上下文將只是.tes
. 這有助于限制子模板的范圍,而不必通過(guò) dot-walk 來(lái)獲得一個(gè)值。
- 1 回答
- 0 關(guān)注
- 523 瀏覽
添加回答
舉報(bào)
0/150
提交
取消