拥有 gin-gonic 网络应用程序。
有3个文件:
1) base.html -- 基础布局文件
<!DOCTYPE html>
<html lang="en">
<body>
header...
{{template "content" .}}
footer...
</body>
</html>
2) page1.html, for/page1
{{define "content"}}
<div>
<h1>Page1</h1>
</div>
{{end}}
{{template "base.html"}}
3) page2.html,用于/page2
{{define "content"}}
<div>
<h1>Page2</h1>
</div>
{{end}}
{{template "base.html"}}
问题是/page1 和/page2 使用一个模板 - page2.html。我想我对这样的结构有误解:{{define "content"}}
, {{template "base.html"}}
。
请举例说明如何在 golang 中使用基本布局?
最佳答案
只要将模板与“内容”一起解析,就可以使用 base.html,如下所示:
基础.html
{{define "base"}}
<!DOCTYPE html>
<html lang="en">
<body>
header...
{{template "content" .}}
footer...
</body>
</html>
{{end}}
page1.html
{{define "content"}}
I'm page 1
{{end}}
page2.html
{{define "content"}}
I'm page 2
{{end}}
然后 ParseFiles 使用 ("your-page.html", "base.html") 和 ExecuteTemplate 使用您的上下文。
tmpl, err := template.New("").ParseFiles("page1.html", "base.html")
// check your err
err = tmpl.ExecuteTemplate(w, "base", yourContext)
关于go - 如何将基础模板文件用于 golang html/模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36617949/