gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:57:35 25 4
gpt4 key购买 nike

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

如果这不可能,我的替代方案是什么。 mustache 似乎是一种选择,但我会错过 html/template 的那些微妙的功能,比如上下文敏感的转义等吗?还有哪些其他选择?

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

感谢阅读。

最佳答案

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

如果您自己创建此类模板集的映射,您将拥有 Jinja/Django 提供的基本相同的灵 active 。唯一的区别是 html/template包无法直接访问文件系统,因此您必须自己解析和组合模板。

考虑以下示例,其中包含两个都继承自“base.html”的不同页面(“index.html”和“other.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 映射。

关于go - 是否可以使用标准库在 Go 中嵌套模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11467731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com