是的,这是可能的.html.Template
实际上是一组模板文件.如果执行此集合中定义的块,它可以访问此集合中定义的所有其他块.
如果您自己创建这类模板集的映射,您基本上可以获得与JJJA/Django相同的灵活性.唯一的区别是html/template包不能直接访问文件系统,因此您必须自己解析和编写模板.
考虑下面的示例,其中包含两个不同的页面("index.html"和"ther.html"),这两个页面都继承自"base.html":
// Content of base.html:
{{define "base"}}<html>
<head>{{template "head" .}}</head>
<body>{{template "body" .}}</body>
</html>{{end}}
// Content of index.html:
{{define "head"}}<title>index</title>{{end}}
{{define "body"}}index{{end}}
// Content of other.html:
{{define "head"}}<title>other</title>{{end}}
{{define "body"}}other{{end}}
和以下模板集图:
tmpl := make(map[string]*template.Template)
tmpl["index.html"] = template.Must(template.ParseFiles("index.html", "base.html"))
tmpl["other.html"] = template.Must(template.ParseFiles("other.html", "base.html"))
现在可以通过调用以下方法呈现"index.html"页面
tmpl["index.html"].Execute("base", data)
你可以通过调用
tmpl["other.html"].Execute("base", data)
使用一些技巧(例如,模板文件的命名约定一致),甚至可以自动生成tmpl
map .