如何在python运行时中获得像Jinja一样的嵌套模板。TBC我的意思是,我如何让一堆模板继承自基础模板,只是像Jinja/django-templates那样在基础模板的块中归档。是否可以在标准库中只使用html/template。
如果这是不可能的,我的选择是什么。胡子似乎是一个选择,但我会错过html/template的那些漂亮的微妙功能,比如上下文相关的转义等吗?还有别的选择吗?
(环境: Google App Engin,Go runtime v1,Dev - Mac OSx lion)
感谢您的阅读。
发布于 2012-07-13 17:53:01
是的,这是可能的。html.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映射。
发布于 2016-06-30 09:57:12
请注意,当您执行基本模板时,您必须将值向下传递给子模板,在这里我只传递".",以便所有内容都向下传递。
模板一显示{{.}}
{{define "base"}}
<html>
<div class="container">
{{.}}
{{template "content" .}}
</div>
</body>
</html>
{{end}}模板2显示传递到父级的{{.domains}}。
{{define "content"}}
{{.domains}}
{{end}}请注意,如果我们使用{{template " content“.}}而不是{{template "content”.}},则无法从内容模板访问.domains。
DomainsData := make(map[string]interface{})
DomainsData["domains"] = domains.Domains
if err := groupsTemplate.ExecuteTemplate(w, "base", DomainsData); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}发布于 2018-10-26 03:38:43
我使用过其他的模板包,现在我主要使用标准的html/模板包,我想我太天真了,没有欣赏到它提供的简单性和其他好处。我使用与接受答案非常相似的方法,但做了以下更改
您不需要使用额外的base模板包装您的布局,每个解析的文件都会创建一个模板块,所以在这种情况下它是多余的,我还喜欢使用新版本go中提供的块操作,它允许您在子模板中没有提供默认块内容的情况下具有默认块内容
// base.html
<head>{{block "head" .}} Default Title {{end}}</head>
<body>{{block "body" .}} default body {{end}}</body>您的页面模板可以与
// 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["index.html"].ExecuteTemplate(os.Stdout, "base.html", data)https://stackoverflow.com/questions/11467731
复制相似问题