我在 Golang 項目中有 3 個文件,想法是在 layout.html 的正文中呈現 index.html。有用。但是當我嘗試將變量傳遞給index.html 時,console.log()沒有呈現。當我移動console.log()到layout.html 時,我可以從.html中看到 JSON 的內容.tes。這是項目文件。布局.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貢獻1786條經驗 獲得超11個贊
在 layout.HTML 中,您需要傳遞上下文。你用一個.
點來做。
{{ template "contents" . }}
或者,您可以傳遞您想要的任何 var 的值:
{{ template "contents" .tes }}
...在內容模板中,點上下文將只是.tes
. 這有助于限制子模板的范圍,而不必通過 dot-walk 來獲得一個值。
- 1 回答
- 0 關注
- 521 瀏覽
添加回答
舉報
0/150
提交
取消