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

如果不可能,我还有什么 Select .留胡子似乎是一种 Select ,但我会错过html/template的那些微妙的功能吗,比如上下文敏感的转义等.?还有什么其他 Select ?

(环境:Google App Engin,Go runtime v1,Dev-Mac OSx lion)

谢谢你的阅读.

推荐答案

是的,这是可能的.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 .

Go相关问答推荐

Golang文本/模板序列范围

Docker Compose Health Check未退出,错误为无法启动

如何执行asn 1 marshal/unmarshal和omit字段?

从MySQL/GO表获取行数据

如何在 Chi Router 的受保护路由下提供静态文件(尤其是图像)?

Cypher 查找(多个)最低 node

为什么 Go 对于长度为 100k 的切片使用的内存比长度为 100k 的数组要少?

使用模拟在 golang 中测试我的界面.专门测试调用同级函数的 1 个函数

使用 unsafe.Pointer 将 struct point直接转换为另一个 struct 是否安全?

golang 中的可变参数函数

读取非UTF8编码的文件内容并正确打印出来

如何过滤来自 fsnotify 的重复系统消息

Go 中的 HTTP 请求验证中间件

try 与 golang testify/suite 并行运行测试失败

在 Raspberry Pi4 上下载 Go Mod

自定义指标未显示在 prometheus web ui 中,grafana 中也是如此

如何在 GORM 中获取字段值

Go 中 SDL Surface 的 OpenGL 纹理

具有多个嵌入式 struct 的 Go MarshalJSON 行为

Go 错误处理、类型断言和 net package包