使用标准库可以在Go中嵌套模板吗? [英] Is it possible to have nested templates in Go using the standard library?

查看:77
本文介绍了使用标准库可以在Go中嵌套模板吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在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.

如果这是不可能的,我有什么选择.胡子似乎是一种选择,但是我会不会错过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)

,您可以通过调用

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆