是否可以使用标准库在 Go 中嵌套模板? [英] Is it possible to have nested templates in Go using the standard library?
问题描述
我如何在 python 运行时中获得像 Jinja 那样的嵌套模板.TBC 我的意思是我如何让一堆模板继承自一个基本模板,只是在基本模板的块中归档,就像 Jinja/django-templates 那样.是否可以在标准库中仅使用 html/template
.
How do I get nested templates like Jinja has in the python runtime. TBC what I mean is how do I have a bunch of templates inherit from a base templates, just filing in blocks of the base templates, like Jinja/django-templates does. Is it possible using just html/template
in the standard library.
如果那不可能,我的选择是什么.Mustache 似乎是一种选择,但是我会不会错过 html/template
那些不错的微妙功能,例如上下文敏感的转义等?还有哪些其他选择?
If that is not a possibility, what are my alternatives. Mustache seems to be an option but would I then be missing out on those nice subtle features of html/template
like the context sensitive escaping etc.? What other alternatives are ther?
(环境:Google App Engin、Go runtime v1、Dev - Mac OSx lion)
(Environment: Google App Engin, Go runtime v1, Dev - Mac OSx lion)
感谢阅读.
推荐答案
是的,这是可能的.html.Template
实际上是一组模板文件.如果您执行此集中定义的块,则它可以访问此集中定义的所有其他块.
Yes it is possible. A html.Template
is actually a set of template files. If you execute a defined block in this set, it has access to all the other blocks defined in this set.
如果您自己创建此类模板集的地图,则基本上具有 Jinja/Django 提供的灵活性.唯一的区别是 html/template 包不能直接访问文件系统,所以您必须自己解析和组合模板.
If you create a map of such template sets on your own, you have basically the same flexibility that Jinja / Django offers. The only difference is that the html/template package has no direct access to the file system, so you have to parse and compose the templates on your own.
考虑以下两个不同页面(index.html"和other.html")的示例,它们都继承自base.html":
Consider the following example with two different pages ("index.html" and "other.html") that both inherit from "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"))
您现在可以通过调用
tmpl["index.html"].Execute("base", data)
并且您可以通过调用呈现您的other.html"页面
and you can render your "other.html" page by calling
tmpl["other.html"].Execute("base", data)
通过一些技巧(例如模板文件的一致命名约定),甚至可以自动生成 tmpl
映射.
With some tricks (e.g. a consistent naming convention of your template files), it's even possible to generate the tmpl
map automatically.
这篇关于是否可以使用标准库在 Go 中嵌套模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!