我在Golang项目中有3个文件,其目的是渲染index.html isnside layout.html的主体。它有效。
但是当我尝试将变量传递到 index.html 时,console.log()
没有呈现。当我将console.log()
移至 layout.html 时,我可以从.tes
看到JSON的内容。
以下是项目文件。
的layout.html
<!DOCTYPE html>
<html lang="en">
<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>
的index.html
{{define "contents"}}
<script>
var x = {{.tes}};
console.log(x)
</script>
{{end}}
router.go
func 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)
}
答案 0 :(得分:3)
在layout.HTML中,您需要传递上下文。你用.
点来做到这一点。
{{ template "contents" . }}
或者,您可以传递任何var所需的值:
{{ template "contents" .tes }}
...在内容模板中,点上下文将只是.tes
的值。这有助于限制子模板的范围,而不必使用dot-walk来获取值。