我在 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 关注
- 548 浏览
添加回答
举报
0/150
提交
取消
