小编典典

是否可以使用标准库在 Go 中嵌套模板?

go

我如何在 python 运行时获得像 Jinja 那样的嵌套模板。TBC 我的意思是我如何让一堆模板继承自一个基本模板,只是在基本模板的块中归档,就像 Jinja/django-templates 那样。是否可以仅html/template在标准库中使用。

如果那不可能,我的选择是什么。Mustache 似乎是一个选择,但我会不会错过那些很好的微妙功能,html/template比如上下文敏感的转义等?还有哪些其他选择?


阅读 259

收藏
2021-12-07

共1个答案

小编典典

对的,这是可能的。Ahtml.Template实际上是一组模板文件。如果您执行此集中定义的块,则它可以访问此集中定义的所有其他块。

如果您自己创建此类模板集的地图,则基本上具有 Jinja / Django 提供的灵活性。唯一的区别是html/template包不能直接访问文件系统,因此您必须自己解析和组合模板。

考虑以下带有两个不同页面(“index.html”和“other.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)

你可以通过调用呈现你的“other.html”页面

tmpl["other.html"].Execute("base", data)

通过一些技巧(例如模板文件的一致命名约定),甚至可以tmpl自动生成地图。

2021-12-07