问题描述
具有gin-gonic网络应用程序.
Have gin-gonic web app.
共有3个文件:
1)base.html-基本布局文件
1) base.html -- base layout file
<!DOCTYPE html>
<html lang="en">
<body>
header...
{{template "content" .}}
footer...
</body>
</html>
2)page1.html,用于/page1
2) page1.html, for /page1
{{define "content"}}
<div>
<h1>Page1</h1>
</div>
{{end}}
{{template "base.html"}}
3)page2.html,用于/page2
3) page2.html, for /page2
{{define "content"}}
<div>
<h1>Page2</h1>
</div>
{{end}}
{{template "base.html"}}
{{define"content"}} {{template"base.html"}}
{{define "content"}}{{template "base.html"}}
请,您能举例说明如何在golang中使用基本布局吗?
Please, can you show an example how to use base layouts in golang?
推荐答案
只要您将模板连同内容"一起解析,就可以使用base.html,如下所示:
You can use the base.html as long as you parse the template along with your "content", like so:
base.html
base.html
{{define "base"}}
<!DOCTYPE html>
<html lang="en">
<body>
header...
{{template "content" .}}
footer...
</body>
</html>
{{end}}
page1.html
page1.html
{{define "content"}}
I'm page 1
{{end}}
page2.html
page2.html
{{define "content"}}
I'm page 2
{{end}}
然后使用("your-page.html","base.html")和 ExecuteTemplate 与您的上下文关联的
tmpl, err := template.New("").ParseFiles("page1.html", "base.html")
// check your err
err = tmpl.ExecuteTemplate(w, "base", yourContext)