如何将基本模板文件用于golang html/template? [英] How to use base template file for golang html/template?
问题描述
具有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"}}
问题是/page1和/page2使用一个模板-page2.html.我认为我对这样的构造有误解: {{define"content"}}
, {{template"base.html"}}
.
The problem is that /page1 and /page2 use one template - page2.html. I think that I have misunderstanding of such constructions: {{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 与您的上下文关联的
then ParseFiles with ("your-page.html", "base.html"), and ExecuteTemplate with your context.
tmpl, err := template.New("").ParseFiles("page1.html", "base.html")
// check your err
err = tmpl.ExecuteTemplate(w, "base", yourContext)
这篇关于如何将基本模板文件用于golang html/template?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!